How to Store an YEAR from DatePickerDialog in Kotlin? - android

So basically i want to get the year from the user using the datePickerDialog and then substract that year to the current year. Till this i have no issues.
The problem is i have button created and want users to get a Toast message if they haven't chosen the date. I am using if else and validating the Year when the datePicker is not selected.
Also the year i am getting after the datePickerDialog is the current year.
Here is the Code -
fun birthdayPicker() {
val cal = Calendar.getInstance()
val year = cal.get(Calendar.YEAR)
val month = cal.get(Calendar.MONTH)
val date = cal.get(Calendar.DATE)
val textcheck : TextView = findViewById(R.id.yourage)
val dateSelected = findViewById<TextView>(R.id.text_view_date_1)
dateSelected.setOnClickListener {
val datePickerDialog = DatePickerDialog(
this,
DatePickerDialog.OnDateSetListener { _, myear, mmonth, mdayOfMonth ->
dateSelected.setText("" + mdayOfMonth + "/" + mmonth + "/" + myear)
// Toast.makeText(this, "$myear", Toast.LENGTH_SHORT).show()
},
year,
month + 1,
date
)
datePickerDialog.show()
}
val button = findViewById<Button>(R.id.button_date_1)
button.setOnClickListener {
val selectedyear : Int = year
if (selectedyear.toString().isBlank()) {
Log.e("Main","$selectedyear")
Toast.makeText(this, "Choose an Year", Toast.LENGTH_SHORT).show()
}
else {
val checkingYear = Calendar.getInstance().get(Calendar.YEAR)
textcheck.text = (checkingYear - selectedyear).toString()
}
}
}

so you just store that into a variable as so
val myFormat = "MM/dd/yyyy" //mention the format you need
val sdf = SimpleDateFormat(myFormat, Locale.US)
val currentDate = sdf.format(cal.getTime())

Related

How to get the days diffence between two date

How to calculate the days between two date for android studio in kotlin. There is two button for choosing date, after choosing the date, I want to compare two date and get the difference day between these two date.
Here is my code
tvDatePicker = findViewById(R.id.textViewDate)
btnDatePicker = findViewById(R.id.btn_datePicker)
EndDatePicker = findViewById(R.id.textViewBookEnd)
btnEndDatePicker = findViewById(R.id.btn_EndDatePicker)
val myCalendar = Calendar.getInstance()
val datePicker = DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
myCalendar.set(Calendar.YEAR,year)
myCalendar.set(Calendar.MONTH,month)
myCalendar.set(Calendar.DAY_OF_MONTH,dayOfMonth)
updateStartDate(myCalendar)
}
val endDatePicker = DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
myCalendar.set(Calendar.YEAR,year)
myCalendar.set(Calendar.MONTH,month)
myCalendar.set(Calendar.DAY_OF_MONTH,dayOfMonth)
updateEndDate(myEndCalendar)
}
btnDatePicker.setOnClickListener{
DatePickerDialog(this,datePicker, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show()
}
btnEndDatePicker.setOnClickListener{
DatePickerDialog(this,endDatePicker, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show()
}
private fun updateStartDate(myCalendar: Calendar){
val myFormat = "dd-MM-yyyy"
val sdf = SimpleDateFormat(myFormat, Locale.UK)
tvDatePicker.setText(sdf.format(myCalendar.time))
}
private fun updateEndDate(myCalendar: Calendar){
val myFormat = "dd-MM-yyyy"
val sdf = SimpleDateFormat(myFormat, Locale.UK)
EndDatePicker.setText(sdf.format(myCalendar.time))
}
private fun dayDifference(startCalendar: Calendar, endCalendar: Calendar): Long {
val diff = endCalendar.timeInMillis - startCalendar.timeInMillis
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS).toInt()
}

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;
}

How to make End Date 1 day after the Start Day on android datePicker

i have a project that should bring end date after the start date on android datepicker.
(user will chose any date on start date and when user click end date what ever user choose end date should be one day after start date)
for this purpose i have a Kotlin code as in below;
private fun showDatePickerDialog(type: Int) {
calendar = Calendar.getInstance()
year = calendar!!.get(Calendar.YEAR)
month = calendar!!.get(Calendar.MONTH)
dayOfMonth = calendar!!.get(Calendar.DAY_OF_MONTH)
datePickerDialog = DatePickerDialog(
requireContext(), R.style.MyDatePickerStyle,
{ datePicker, year, month, day ->
if (type == 0){
var month = month + 1
var startMonthConverted = ""+month
var startDayConverted = ""+day
if(month<10){
startMonthConverted = "0$startMonthConverted"
}
if(day<10){
startDayConverted= "0$startDayConverted"
}
binding.txtStartDate.setText("$year-$startMonthConverted-$startDayConverted")
} else {
var month = month + 1
var monthConverted = ""+month
var dayConverted = ""+day
if(month<10){
monthConverted = "0$monthConverted";
}
if(day<10){
dayConverted = "0$dayConverted"
}
binding.txtEndDate.setText("$year-$monthConverted-$dayConverted")
}
},
year,
month,
dayOfMonth
)
if (type == 0) {
val startDay = Calendar.getInstance()
startDay.add(Calendar.DAY_OF_YEAR, 2);
datePickerDialog!!.datePicker.minDate = startDay.timeInMillis
} else {
val endDay = Calendar.getInstance()
endDay.add(Calendar.DATE, 2)
// datePickerDialog!!.datePicker.minDate = endDay.timeInMillis
datePickerDialog!!.getDatePicker().setMinDate(endDay.getTimeInMillis());
}
val df: DateFormat = SimpleDateFormat("'T'HH:mm:ss.SSS")
currentTime = df.format(Calendar.getInstance().timeInMillis)
Log.d("TAG", "currentTime:$currentTime ")
datePickerDialog!!.show()
//set OK/Cancel buttons color
//set OK/Cancel buttons color
datePickerDialog!!.getButton(Dialog.BUTTON_POSITIVE)
.setTextColor(android.graphics.Color.BLACK)
datePickerDialog!!.getButton(Dialog.BUTTON_NEGATIVE)
.setTextColor(android.graphics.Color.BLACK)
}

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.

DatePicker dialog may showing improper date in kotlin

Below is the function I am using to diplay date picker dialog in android.
private fun openPurchaseDatePickerDialog(
yearToDisplay: Int,
monthToDisplay: Int,
dayToDisplay: Int
) {
try {
activity?.let { KeyboardUtils.hideKeyboard(it) }
val calendar = Calendar.getInstance()
val dialog = DatePickerDialog(activity, { _, year, month, day_of_month ->
calendar[Calendar.YEAR] = year
calendar[Calendar.MONTH] = month
calendar[Calendar.DAY_OF_MONTH] = day_of_month
val myFormat = "" + DateUtils.OverAllAppDateDisplayFormat
val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
edtPurchaseDate.setText(sdf.format(calendar.time).toString())
spIntendedUse.isFocusable = true
}, yearToDisplay, monthToDisplay, dayToDisplay)
dialog.updateDate(yearToDisplay,monthToDisplay,dayToDisplay)
dialog.datePicker.maxDate = calendar.timeInMillis
dialog.show()
} catch (e: Exception) {
e.printStackTrace()
}
As above you can check that there are three arguments passed in this function.
I have to show the specific date in DatePicker dialog show I have passed this three parameters.
Means If User selected the date first time the default values will be set or the current date will be set.
If edittext has already a text selected and not empty am doing as below :
if (edtPurchaseDate.text.toString().isNullOrEmpty()) {
val calendar = Calendar.getInstance()
openPurchaseDatePickerDialog(
calendar[Calendar.YEAR],
calendar[Calendar.MONTH],
calendar[Calendar.DAY_OF_MONTH]
)
} else {
var dateArr = edtPurchaseDate.text.toString().split("-")
openPurchaseDatePickerDialog(
dateArr[2].toInt(),
dateArr[1].toInt(),
dateArr[0].toInt()
)
}
But Still when the date picker dialogs opens its displaying the selected as as today instead of custom.
What might be the issue?
You can see I have also tried with updateDate() function as below :
dialog.updateDate(yearToDisplay,monthToDisplay,dayToDisplay)
Thanks.
Not completely sure about the updateDate method issue here . But to fix this you can use same Calendar object during initialization it should work fine .
i have modified your method a bit .
private fun openPurchaseDatePickerDialog(date: String) {
try {
val calendar = Calendar.getInstance()
if (date.isNotBlank()) {
try {
calendar.time = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).parse(date)!!
}catch (e:ParseException){
}
}
val dialog = DatePickerDialog(this, { _, year, month, day_of_month ->
calendar[Calendar.YEAR] = year
calendar[Calendar.MONTH] = month
calendar[Calendar.DAY_OF_MONTH] = day_of_month
val myFormat = "dd-MM-yyyy"
val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
edtPurchaseDate.setText(sdf.format(calendar.time).toString())
}, calendar[Calendar.YEAR], calendar[Calendar.MONTH], calendar[Calendar.DAY_OF_MONTH])
dialog.datePicker.maxDate = System.currentTimeMillis()
dialog.show()
} catch (e: Exception) {
e.printStackTrace()
}
}
Now when you call it you just call it with a value you do mnot have to split String.
openPurchaseDatePickerDialog(edtPurchaseDate.text.toString())

Categories

Resources