How can I get selected date in CalenderView in Android? - android

Calendar date = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
curDate = sdf.format(date.getTime());
I have done the above code inside onCreate method. But it can only return the current date. What I want is to have the date selected in the calender.
<CalendarView
android:id="#+id/calendarView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Please help me

I used CalendarView instead of Calender and it's working now.
calendarView.setOnDateChangeListener(new OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month,
int dayOfMonth) {
curDate = String.valueOf(dayOfMonth);
}
});

You can get Selected date using Calendar view Like this...
CalendarView calendarView=view.findViewById(R.id.calendarView);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month,
int dayOfMonth) {
String curDate = String.valueOf(dayOfMonth);
String Year = String.valueOf(year);
String Month = String.valueOf(month);
Log.e("date",Year+"/"+Month+"/"+curDate);
}
});

Example code in Kotlin to fetch selected date in CalenderView:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<CalendarView
android:id="#+id/calendar_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Toast Selected Date" />
</LinearLayout>
MainActivity.kt
import android.os.Bundle
import android.text.format.DateFormat
import android.util.Log
import android.widget.CalendarView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.testandcheck.databinding.ActivityMainBinding
import java.util.*
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding // Binding object for ViewBinding.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// Set date change listener on calenderView.
// Callback notified when user select a date from CalenderView on UI.
binding.calendarView.setOnDateChangeListener { calView: CalendarView, year: Int, month: Int, dayOfMonth: Int ->
// Create calender object with which will have system date time.
val calender: Calendar = Calendar.getInstance()
// Set attributes in calender object as per selected date.
calender.set(year, month, dayOfMonth)
// Now set calenderView with this calender object to highlight selected date on UI.
calView.setDate(calender.timeInMillis, true, true)
Log.d("SelectedDate", "$dayOfMonth/${month + 1}/$year")
}
// Example button to show get selected date from CalenderView and show in Toast.
binding.button.setOnClickListener {
// Fetch long milliseconds from calenderView.
val dateMillis: Long = binding.calendarView.date
// Create Date object from milliseconds.
val date: Date = Date(dateMillis)
// Get Date values and created formatted string date to show in Toast.
val selectedDayOfWeek = DateFormat.format("EEEE", date) as String // Monday
val selectedDay = DateFormat.format("dd", date) as String // 05
val selectedMonthString = DateFormat.format("MMM", date) as String // Jul
val selectedMonthNumber = DateFormat.format("MM", date) as String // 6 --> Month Code as Jan = 0 till Dec = 11.
val selectedYear = DateFormat.format("yyyy", date) as String // 2021
val strFormattedSelectedDate = "$selectedDay-${selectedMonthNumber + 1}-$selectedYear ($selectedDayOfWeek)"
Toast.makeText(applicationContext, "Selected Date = $strFormattedSelectedDate", Toast.LENGTH_SHORT).show()
}
}
}
Explaination:
Set listener to set selected date in CalenderView (also highlight the newly selected date and un-highlight the older date).
Then only call calenderView.date to get selected date.

Did you try Calendar.get(Calendar.DATE)
Check the link GetDate() Calendar

final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
final DateFormat dateFormat_year = new SimpleDateFormat("yyyy");
final DateFormat dateFormat_month = new SimpleDateFormat("MM");
final DateFormat dateFormat_day = new SimpleDateFormat("dd");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
System.out.println(dateFormat_year.format(cal.getTime()));
System.out.println(dateFormat_month.format(cal.getTime()));
System.out.println(dateFormat_day.format(cal.getTime()));

Related

How do I calculate age from my date picker?

I am learning Kotlin on my own. I am trying to calculate the age of a user after the have input their date of Birth and display it in another activity.
I tried a bunch of different stuff and none worked. I'm sure I maybe overlooking something simple.
my code:
class MainActivity : AppCompatActivity() {
var date1: EditText? = null
var datePickerDialog: DatePickerDialog? = null
lateinit var submitButton: Button
lateinit var userInput: EditText
lateinit var dob: EditText
#SuppressLint("SetTextI18n", "MissingInflatedId", "CutPasteId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(layout.activity_main)
date1 = findViewById<EditText>(id.date) as EditTe
date1!!.setOnClickListener{ // calender class's instance and get current date , month and year from calender
val c = Calendar.getInstance()
val mYear = c[Calendar.YEAR] // current year
val mMonth = c[Calendar.MONTH] // current month
val mDay = c[Calendar.DAY_OF_MONTH] // current day
datePickerDialog = DatePickerDialog(
this#MainActivity,
{ view, year, monthOfYear, dayOfMonth -> // set day of month , month and year value in the edit text
date1!!.setText(
dayOfMonth.toString() + "/"
+ (monthOfYear + 1) + "/" + year
)
}, mYear, mMonth, mDay
)
datePickerDialog!!.show()
}
submitButton = findViewById(id.sub_btn)
userInput = findViewById(id.username1)
dob = findViewById(id.date)
submitButton.setOnClickListener {
val age= dob.text.toString()
val name= userInput.text.toString()
//val str = userInput.text.toString()
intent = Intent(this, CardReturn::class.java)
intent.putExtra("message_key","Name:$name")
intent.putExtra("message_key1","DOB:$age")
startActivity(intent)
}
}}
If you're able to utilize java.time or at least ThreeTen Android Backport, it should be easy and will save you from a lot of work if your'e using java.util.Calendar.
Here's a small working piece of DatePickerDialog that you can copy and paste easily, this is how I calculate year difference between two LocalDate instance
val now = LocalDateTime.now()
val initYear = now.year
val initMonth = now.monthValue - 1 // offset it -1 because January starts at 0 index
val initDay = now.dayOfMonth
val datePickerDialog = DatePickerDialog(
this#ActivityOrContext,
{ _: DatePicker, pickedYear: Int, pickedMonth: Int, pickedDay: Int ->
val selectedBirthdate = LocalDate.of(pickedYear, pickedMonth + 1, pickedDay)
val age = Period.between(selectedBirthdate, LocalDate.now()).years
Log.e("DatePickerTag", "Age : $age")
}, initYear, initMonth, initDay)
If I select April 1 1995 and evaluate it against the time of this posting it will print
E/DatePickerTag: Age : 27
If however you can't use java.time or ThreeTenABP, this S.O post might help you otherwise. The bottom section of the post contains answers for calculating age using java.util.Calendar.
Lastly, out-of-topic, consider what lateinit var is for, what kotlin null safety is, and avoid shouting in your code unnecessarily!!
Inside layout file
<DatePicker
android:id="#+id/ageSelectionPicker"
style="#style/MyDatePicker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginTop="16dp"
android:layout_marginRight="24dp"
android:backgroundTint="#ff4081"
android:calendarTextColor="#ff4081"
android:calendarViewShown="false"
android:datePickerMode="spinner" />
class.java
DatePicker ageSelectionPicker = findViewById(R.id.ageSelectionPicker);
int age = getAge(ageSelectionPicker.getYear(), ageSelectionPicker.getMonth(), ageSelectionPicker.getDayOfMonth());
Method getAge
private int getAge(int year, int month, int day) {
Calendar dateOfBirth = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dateOfBirth.set(year, month, day);
int age = today.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dateOfBirth.get(Calendar.DAY_OF_YEAR)) {
age--;
}
return age;
}

Set date and get Date from Material Date Picker in Kotlin Android

I'm learning kotlin and at the moment I don't know much, I want to change a datepicker that I have for one of type Material, the problem is that I don't know how to pass the data to this new date picker.
This is the one I have at the moment:
fecha = view.findViewById(R.id.fecha)
fecha?.setOnClickListener {
fecha!!.error = null
val dateSetListener = DatePickerDialog(requireContext(), { _, year, monthOfYear, dayOfMonth ->
cal.set(Calendar.YEAR, year)
mYear = year
cal.set(Calendar.MONTH, monthOfYear)
mMonth = monthOfYear
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
mDay = dayOfMonth
updateDateInView()
}, mYear, mMonth, mDay)
dateSetListener.datePicker.maxDate = System.currentTimeMillis()
dateSetListener.show()
}
fun updateDateInView() {
val myFormat = "dd/MM/yyyy"
val sdf = SimpleDateFormat(myFormat)
fecha?.setText(sdf.format(cal.time))
}
I want to make it like this but I don't know how to pass and save the values, could someone help me?
val datePicker = MaterialDatePicker.Builder.datePicker().build()
MaterialDatePicker accepts CalendarConstraints to open the date picker on a certain month. CalendarConstraints accepts timeInMilliseconds to open calendar on a particular month. MaterialDatePicker has an addOnPositiveButtonClickListener method whose lambda returns the time in milliseconds after the user makes a selection.
You can create MaterialDatePicker like this
val myFormat = "dd/MM/yyyy"
val formattedDate = "01/01/2000"
val sdf = SimpleDateFormat(myFormat)
val date = sdf.parse(formattedDate)
val timeInMillis = date.time
val constraintBuilder = CalendarConstraints.Builder().setOpenAt(
timeInMillis //pass time in milli seconds
).build()
val picker = MaterialDatePicker.Builder.datePicker()
.setTitleText("Select Date")
.setCalendarConstraints(constraintBuilder)
.build()
picker.addOnPositiveButtonClickListener {
val date = Date(it)
val formattedDate = sdf.format(date) // date selected by the user
}
// show picker using this
picker.show(requireActivity().supportFragmentManager, "materialDatePicker")
Instead of using SimpleDateFormatter, you should use LocalDateTime API provided in Java8
Using LocalDateTime API, you can do the same like this
val dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.getDefault())
val formattedDate = "01/01/2000"
val timeInMillis = LocalDate.parse(formattedDate, dateFormatter)
.atStartOfDay(ZoneId.systemDefault())
.toInstant()
.toEpochMilli()
You can pass this timeInMillis to setOpenAt() method of CalendarConstraintSet.
To get the date after the user makes a selection
val timeInMillis = dateFormatter.format(
// it is the milliseconds received inside lambda of addOnPositiveButtonClickListener
Instant.ofEpochMilli(it)
.atZone(ZoneId.systemDefault()).toLocalDate()
)

My app is closing after i pic the date , can anyone help me , i have attatched the code

This is my code and it crashes after i select the date in date picker dialog
bdaybutton.setOnClickListener { view -\\\>
val c = Calendar.getInstance()
val cyear = c.get(Calendar.YEAR)
val cmonth = c.get(Calendar.MONTH)
val cday = c.get(Calendar.DAY_OF_MONTH)
val abc = DatePickerDialog( this , DatePickerDialog.OnDateSetListener
{ view , year, month, day -\\\>
flag2 = true
year2 = year
val selecteddate = "${day/month+1/year}"
bdaydatetext.text = "${day/month+1/year}"
val sdf = java.text.SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH)
val date2 = sdf.parse(selecteddate)
time2 = date2.time.toInt()
}, cyear, cmonth, cday)
abc.show()
]
}
The error in the imge appears when after selecting the date
"${day/month+1/year}"
This computes the expression inside the {} and converts it to a string. Looks like you wanted something like
"${day}/${month+1}/${year}"
instead there.
Better yet, skip the string conversion step altogether and use something like Java 8 LocalDate or LocalDateTime directly instead.

Get Day Name from date picker?

I want to get date in this format "Saturday, 6/10/2018" from the Date Picker Dialog. The problem is that when I select any date from current month it displays true output but when I select any date from previous or next month it displays wrong name of day of the week.
Note: Previously asked questions doesn't helped me...
Here is my code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="#+id/pickDateBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="200dp"
android:text="Pick Full Date" />
<TextView
android:id="#+id/displayDateTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Full Date will display here..."
android:textColor="#000"
android:textSize="20sp" />
</LinearLayout>
MainActivity.kt
package com.blogspot.atifsoftwares.fulldateformat
import android.app.DatePickerDialog
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
pickDateBtn.setOnClickListener {
pickDate()
}
}
private fun pickDate() {
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, mYear, monthOfYear, dayOfMonth ->
val simpleDateFormat = SimpleDateFormat("EEEE")
val date = Date(mYear, month, dayOfMonth - 1)
val dayString = simpleDateFormat.format(date) //returns true day name for current month only
displayDateTv.text = "$dayString, $dayOfMonth/${monthOfYear + 1}/$mYear"
}, year, month, day)
dpd.show()
}
}
val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, mYear, monthOfYear, dayOfMonth ->
val simpleDateFormat = SimpleDateFormat("EEEE")
val date = Date(mYear, month, dayOfMonth - 1)
val dayString = simpleDateFormat.format(date) //returns true day name for current month only
displayDateTv.text = "$dayString, $dayOfMonth/${monthOfYear + 1}/$mYear"
}, year, month, day)
Change
val date = Date(mYear, month, dayOfMonth - 1)
to val date = Date(mYear, monthOfYear, dayOfMonth - 1)
Explaination : you are using closure month variable not the one you got in lambda while initializing Date class.
val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, mYear, monthOfYear, dayOfMonth ->
val simpleDateFormat = SimpleDateFormat("EEEE")
val date = Date(mYear, monthOfYear, dayOfMonth - 1)
val dayString = simpleDateFormat.format(date) //returns true day name for current month only
displayDateTv.text = "$dayString, $dayOfMonth/${monthOfYear + 1}/$mYear"
}, year, month, day)
You were using closure month variable not the one you got in lambda while initializing Date class. Check this edited code.

How to show only day and month in date picker dialog in Kotlin(Android)?

I have a datepicker dialog. I only want to show day and month. Year picker dialog must hidden. I already tries other answers like this . Nothing works for me. It should also support for Kitkat to Nougat devices. My datepicker code follows.
fun setDatePickerDialog() {
mDobDialog = DatePickerDialog(this#SignUpActivity, R.style.VDDatePickerDialogTheme, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
val newDate = Calendar.getInstance()
newDate.set(year, monthOfYear, dayOfMonth)
//dob_textview.setText("($dayOfMonth) ($monthOfYear) ($year)")
val dateFormat = SimpleDateFormat(VDAppConstants.DOB_DISPLAY_FORMAT)
dob_textview?.setText(dateFormat.format(newDate.time))
}, mNewCalendar.get(Calendar.YEAR), mNewCalendar.get(Calendar.MONTH), mNewCalendar.get(Calendar.DAY_OF_MONTH))
mNewCalendar.set(1978,
mNewCalendar.get(Calendar.MONTH),
mNewCalendar.get(Calendar.DAY_OF_MONTH))
mDobDialog?.datePicker?.maxDate = mNewCalendar.timeInMillis
}
The following code only works on Kitkat devices but not working on Nougat Devices.
val mDobDialog = DatePickerDialog(this#MainActivity, android.R.style.Theme_Holo_Dialog, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
// Display Selected date in textbox
//date.setText("" + dayOfMonth + " " + monthOfYear + ", " + year)
}, year, month, day)
mDobDialog.show()
// Hide Year Selector in Date Picker
mDobDialog.findViewById(Resources.getSystem().getIdentifier("year", "id", "android")).visibility = View.GONE
I tested with different code and this code works fine. If you use datepicker theme as Theme_Holo_Dialog then it working fine. Working code as per below.
Note: It's not working if you set theme Theme_Material_Dialog
package com.wave18.datepickedialogdemo
import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.content.res.Resources
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Date Picker Dialog
val dialog = datePickerDialog()
// Button for Showing Date Picker Dialog
button_show_date_picker.setOnClickListener {
// Show Date Picker
dialog.show()
// Hide Year Selector
val year = dialog.findViewById<View>(Resources.getSystem().getIdentifier("android:id/year", null, null))
if (year != null) {
year.visibility = View.GONE
}
}
}
// Function for Showing Date Picker
#SuppressLint("SetTextI18n")
fun datePickerDialog(): DatePickerDialog {
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
// Date Picker Dialog
val datePickerDialog = DatePickerDialog(this#MainActivity, android.R.style.Theme_Holo_Dialog, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
// Display Selected date in textbox
date.text = "$dayOfMonth $monthOfYear, $year"
}, year, month, day)
// Show Date Picker
return datePickerDialog
}
}

Categories

Resources