Why calendar.add() return 31/9/2018

1.6k Views Asked by At

I want add 2 days from today (29/9/2018), i use:

val calendar = Calendar.getInstance()!!
calendar.set(CalendarDay.today().year, CalendarDay.today().month+1, CalendarDay.today().day)
calendar.add(Calendar.DAY_OF_MONTH, 2)

But when i Log() it, date isn't 1/10/2018, it's 31/9/2018

1

There are 1 best solutions below

3
On BEST ANSWER

For the older API you have chosen to use, you can simplify this to:

val today = Calendar.getInstance()                  // 2018-09-29
today.add(Calendar.DAY_OF_MONTH, 2);                // 2018-10-01

println(SimpleDateFormat().format(today.getTime())) // 2018-10-01

There is no need to set the Calendar instance which already contains the current date.

Your output I think maybe you misread or there is some odd bug in Android implementation because this code:

val today = Calendar.getInstance()                   // 2018-09-29

// totally unneccessary:
today.set(today.get(Calendar.YEAR),  
          today.get(Calendar.MONTH), 
          today.get(Calendar.DAY_OF_MONTH))          // 2018-09-29

today.add(Calendar.DAY_OF_MONTH, 2);                 // 2018-10-01

println(SimpleDateFormat().format(today.getTime()))  // 2018-10-01

Works fine although has the unnecessary step (setting it to be the date it already is). And if you add one to the month as you did before you would create the wrong date:

val today = Calendar.getInstance()                  // 2018-09-29

// unnecessary and wrong:
today.set(today.get(Calendar.YEAR), 
          today.get(Calendar.MONTH)+1, 
          today.get(Calendar.DAY_OF_MONTH))         // 2018-10-29

today.add(Calendar.DAY_OF_MONTH, 2);                // 2018-10-31

println(SimpleDateFormat().format(today.getTime())) // 2018-10-31

If you can use the newer JSR 310 API's that are available on newer Android, then it is better and that solution would be (assuming you wanted to use LocalDate):

val today = LocalDate.now()                           // 2018-09-29
val inTwoDays = today.plusDays(2)                     // 2018-10-01

println(DateTimeFormatter.ISO_DATE.format(inTwoDays)) // 2018-10-01

Please read about the java.time package for more classes that work with dates, calendars, time zones and more.