0

I have the following Code that updates my Calendar object.

val date = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
    myCalendar.set(year, monthOfYear, dayOfMonth)
    myCalendar.set(Calendar.HOUR, myCalendar.get(Calendar.HOUR))
    myCalendar.set(Calendar.MINUTE, myCalendar.get(Calendar.MINUTE))
    myCalendar.set(Calendar.SECOND, myCalendar.get(Calendar.SECOND))
    updateDate()
}

I receive the following values:

year = 2019
month = 11
day = 31

But when I execute the following code i obtain year = 2020:

private fun updateDate()
{
    val myFormat = "dd/MM/YYYY HH:mm:ss"
    val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
    date_et.setText(sdf.format(myCalendar.time))
}

myCalendar.time gives me the following string: Tue Dec 31 11:47:00 GMT+01:00 2019

But on date_et appears the following one: 31/12/2020 11:47:00

Why I have 2019 on Calendar and appears 2020 on my view?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Lechucico
  • 1,914
  • 7
  • 27
  • 60
  • val myFormat = "dd/MM/yyyy HH:mm:ss" - replace Y to "y" – Nik Jan 03 '20 at 10:59
  • @Nik with yyyy it's working. Why? – Lechucico Jan 03 '20 at 11:01
  • ah,With the simple date format (myDateTime. format('MM/dd/YYYY h:mm a')), the year increases here is your prob – shadow Jan 03 '20 at 11:02
  • 2
    @Lechucico @"YYYY" is week-based calendar year. @"yyyy" is ordinary calendar year. – Nik Jan 03 '20 at 11:04
  • 1
    As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Jan 03 '20 at 23:47
  • 1
    (A) Always search Stack Overflow thoroughly before posting. (B) You *really* should be moving on to *java.time* classes. – Basil Bourque Jan 04 '20 at 00:24

1 Answers1

2

Replace

val myFormat = "dd/MM/YYYY HH:mm:ss"

To

val myFormat = "dd/MM/yyyy HH:mm:ss"
Nik
  • 1,991
  • 2
  • 13
  • 30