setting the day field in a calendar using
myCalender.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
does is put set the day to the next Friday or the past Friday or maybe the closest?
Also what if I don't set the year or any other field for the calendar, what are the default values?
it turns out that using
myCalender.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY)
is a complete mess, it may set the day to next or the past Friday, I have been trying a lot but couldn't figure the logic!Anyway, all I needed was to set the calendar to a particular day in the next week, and I managed to do this using the answer to that question ..
set the calendar to next Thursday
next time/date, therefore, the answer is next Friday.
see the documentation
Neither. Yet. It’s complicated. But don’t use
Calendar
, see below.From the documentation of the two-arg
set
method:So during this call it just sets the day-of-week field to Friday. The year, month and day-of-month stay the same, that is, the date isn’t effectively changed. Yet.
If and when the
Calendar
eventually computes and resolves its fields,If you have only set the day of week (which will likely have introduced a conflict with the other fields), the following combination applies:
So it will pick the Friday in the same week.
What defines a week is determined by the
Calendar
’s first-day-of-week field. Its initial value is determined by theCalendar
’s locale, and you can control it throughgetFirstDayOfWeek()
andsetFirstDayOfWeek()
. This in turn means that the default behaviour for aCalendar
in a European locale previously set to a Sunday will go back to the previous Friday, whereas aCalendar
in the US locale would pick the next Friday instead.If you have also set other fields after setting the day-of-week but before fields are calculated, it is a different story.
Default values?
Generally the default values of
Calendar
fields are current date and time in your JVM’s time zone (usually, but not always, the same as your device’s time zone).You don’t need to care
The good news is that you don’t need to care. The
Calendar
class is long outmoded anyway, and it was also (seen in retrospect) poorly designed, so you should not use it. Instead usejava.time
, the modern Java date and time API. It is so much nicer to work with. Depending on your need, you may for example useLocalDate
for a date orZonedDateTime
for a date and time of day with time zone.The modern classes offer you a great deal of better clarity and more flexibility. For example:
Question: Can I use
java.time
on Android?Yes,
java.time
works nicely on Android devices. It just requires at least Java 6.org.threeten.bp
and subpackages.Links
java.time
.Its will be nex Friday
Friday, 23 February 2018 year., 20:44:17.353
Default values is this Year