Reputation: 936
I want to set a given calendar instance's timestamp to the beginning of the week (Monday) and instead it returns a seemingly completely unrelated timestamp - unless I access any of the calendar's fields before doing so. I include a sample below, please also see this runnable example in Ideone.
Is this expected behavior? What's the logic behind this? And yes, I've heard of Joda Time.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
class MyTest {
private static Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CET"), Locale.FRANCE);
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
public static void main(String[] args) {
// Set to any date.
calendar.set(2013, 10, 3);
System.out.println(dateFormat.format(calendar.getTime()));
// Set to another day.
calendar.set(2014, 0, 15);
// --- THE WTF STARTS HERE ---
// Uncommenting the line below returns the correct date in the end.
// calendar.getTime();
// Set to monday of current week.
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
// Expected outdate is 20140113
System.out.println(dateFormat.format(calendar.getTime()));
}
}
Upvotes: 4
Views: 517
Reputation: 338604
LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) // Get the current date for a particular region.
.with(
TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) // Move to an earlier date that is Monday, or stay on same date if it already *is* Monday.
) // Return `LocalDate` object.
The Calendar
class is now legacy, supplanted by the java.time classes, specifically ZonedDateTime
. So the Question is now moot.
Among the problems with the legacy class is that the definition of the start-of-week varies by locale, and crazy numbering schemes for year, month, and day-of-week. In contrast, java.time by default always considers Monday the start of the week, running through Sunday, per the ISO 8601 standard. And java.time using sane numbering:
2018
is the year 2018, no messy math with 1900.LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month
enum objects pre-defined, one for each month of the year. Tip: Use these Month
objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
To move from one date to another, use a TemporalAdjuster
implementation found in TemporalAdjusters
class. Specify the desired day-of-week using DayOfWeek
enum.
LocalDate previousOrSameMonday = today.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Upvotes: 0
Reputation: 1140
Field Manipulation chapter in the docs explains it clearly. It just works weird though.
http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html
Example: Consider a GregorianCalendar originally set to August 31, 1999. Calling set(Calendar.MONTH, Calendar.SEPTEMBER) sets the date to September 31, 1999. This is a temporary internal representation that resolves to October 1, 1999 if getTime()is then called. However, a call to set(Calendar.DAY_OF_MONTH, 30) before the call to getTime() sets the date to September 30, 1999, since no recomputation occurs after set() itself.
EDIT
From the Calendar Fields Resolution part of the same doc
If there is any conflict in calendar field values, Calendar gives priorities to
calendar fields that have been set more recently. The following are the default
combinations of the calendar fields. The most recent combination, as determined
by the most recently set single field, will be used.
For the date fields:
YEAR + MONTH + DAY_OF_MONTH
YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
YEAR + DAY_OF_YEAR
YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
I think the difference between MONTH and DAY_OF_WEEK is this. If you set MONTH at the last statement it matches with YEAR+MONTH+DAY_OF_MONTH and overrides all of them. If you set DAY_OF_WEEK it matches with YEAR+DAY_OF_WEEK+WEEK_OF_YEAR so doesn't override the month value. Or something like that. To be honest, the more I look the more broken it seems. It doesn't make sense at all. Better keep using JodaTime
Upvotes: 5
Reputation: 1230
Can you clear the calendar as it retains values?
Kaya's answer about why this would be relevant
E.g:
calendar.clear();
// Set to another day.
calendar.set(2014, 0, 14);
This returns:
20140113 rather than 20131223 as you were previoiusly getting.
From the docs:
void java.util.Calendar.set(int year, int month, int date)
Sets the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH. Previous values of other calendar fields are retained. If this is not desired, call clear() first.
Upvotes: 1