I came across a comment in some java code that states that getTime() needs to be called to update the Calendar object. Is this true? I cannot find anything that says that this is necessary.
Here's the code:
Calendar cal = new GregorianCalendar();
cal.setFirstDayOfWeek(Calendar.SUNDAY);
cal.set(2009, 9 - 1, 10, 2, 30);
// Get Time needs to be called to update the Calendar object
cal.getTime();
cal.getTime() does indeed need to be called to re-calculate its internals. It is very strange behavior for the API but the Calendar javadocs state this explicitly:
Getting and Setting Calendar Field Values
The calendar field values can be set by calling the set methods. Any
field values set in a Calendar will not be interpreted until it needs
to calculate its time value (milliseconds from the Epoch) or values of
the calendar fields. Calling the get, getTimeInMillis, getTime, add
and roll involves such calculation.
...
Field Manipulation
The calendar fields can be changed using three methods: set(), add(),
and roll(). set(f, value) changes calendar field f to value. In
addition, it sets an internal member variable to indicate that
calendar field f has been changed. Although calendar field f is
changed immediately, the calendar's time value in milliseconds is not
recomputed until the next call to get(), getTime(), getTimeInMillis(),
add(), or roll() is made. Thus, multiple calls to set() do not trigger
multiple, unnecessary computations. As a result of changing a calendar
field using set(), other calendar fields may also change, depending on
the calendar field, the calendar field value, and the calendar system.
In addition, get(f) will not necessarily return value set by the call
to the set method after the calendar fields have been recomputed. The
specifics are determined by the concrete calendar class.
The behavior is unexpected and does not always occur but the following unit tests should exemplify this behavior and always occur.
/**
* Fails the assertion due to missing getTime()
* #throws ParseException
*/
public class DateTest {
#Test
public void testNoGetTime() throws ParseException {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date testDate = df.parse("04/15/2013");
Calendar testCal = Calendar.getInstance();
testCal.setTime(testDate);
Date expectedDate = df.parse("04/04/2013");
Date actualDate = null;
testCal.set(Calendar.DAY_OF_MONTH, testCal.getMinimum(Calendar.DAY_OF_MONTH));
//testCal.getTime();
testCal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
testCal.add(Calendar.DAY_OF_MONTH, -1);
actualDate = testCal.getTime();
assertEquals("Dates should be equal", expectedDate.toString(), actualDate.toString());
}
#Test
public void testWithGetTime() throws ParseException {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date testDate = df.parse("04/15/2013");
Calendar testCal = Calendar.getInstance();
testCal.setTime(testDate);
Date expectedDate = df.parse("04/04/2013");
Date actualDate = null;
testCal.set(Calendar.DAY_OF_MONTH, testCal.getMinimum(Calendar.DAY_OF_MONTH));
testCal.getTime();
testCal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
testCal.add(Calendar.DAY_OF_MONTH, -1);
actualDate = testCal.getTime();
assertEquals("Dates should be equal", expectedDate.toString(), actualDate.toString());
}
}
#skaffman Answer is NOT CORRECT.
Here is an example which proves what I am saying.
//Create an Calendar object set to todays date & time
Calendar calendar = Calendar.getInstance();
Log.d(Tag, "Now : "+ calendar.toString());
//Set the Calendar to the first day of Month
calendar.set(Calendar.DAY_OF_MONTH,1);
Log.d(Tag, "Calendar.DAY_OF_MONTH,1: "+ calendar.toString());
This is the Log.d output:
Now : java.util.GregorianCalendar[time=1478834995641,areFieldsSet=true,lenient=true,zone=America/Chicago,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2016,MONTH=10,WEEK_OF_YEAR=46,WEEK_OF_MONTH=2,DAY_OF_MONTH=10,DAY_OF_YEAR=315,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=29,SECOND=55,MILLISECOND=641,ZONE_OFFSET=-21600000,DST_OFFSET=0] Calendar.DAY_OF_MONTH,1:
Calendar.DAY_OF_MONTH,1: java.util.GregorianCalendar[time=?,areFieldsSet=false,lenient=true,zone=America/Chicago,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2016,MONTH=10,WEEK_OF_YEAR=46,WEEK_OF_MONTH=2,DAY_OF_MONTH=1,DAY_OF_YEAR=315,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=29,SECOND=55,MILLISECOND=641,ZONE_OFFSET=-21600000,DST_OFFSET=0]
If you take time to check it:
The calendar at the beginning shows:
time=1478834995641
DAY_OF_MONTH=10
DAY_OF_YEAR=315
However, when you set it to the first day of the month:
time=?
DAY_OF_MONTH=1
DAY_OF_YEAR=315
Yes, it changed the first day of the month as we wanted, nevertheless some attributes remain the same. For instance, how it comes we set the calendar to DAY_OF_MONTH=1 but we are still in DAY_OF_YEAR=315.
If we use any of the following functions, it will force the Calendar to update.
Calling the get, getTimeInMillis, getTime, add and roll.
From the Calendar Class in Javadocs Check :Getting and Setting Calendar Field Values
To fix it, we add the following code calendar.getTimeInMillis(); which forces the Calendar to update its attributes.
//Create an Calendar object set to todays date & time
Calendar calendar = Calendar.getInstance();
Log.d(Tag, "Now : "+ calendar.toString());
//Set the Calendar to the first day of Month
calendar.set(Calendar.DAY_OF_MONTH,1);
//UPDATE BY CALLING getTimeInMillis() or any of the previously mentioned functions
calendar.getTimeInMillis();
Log.d(Tag, "Calendar.DAY_OF_MONTH,1: "+ calendar.toString());
Now, lets Check Results:
Now : java.util.GregorianCalendar[time=1478836452183,areFieldsSet=true,lenient=true,zone=America/Chicago,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2016,MONTH=10,WEEK_OF_YEAR=46,WEEK_OF_MONTH=2,DAY_OF_MONTH=10,DAY_OF_YEAR=315,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=54,SECOND=12,MILLISECOND=183,ZONE_OFFSET=-21600000,DST_OFFSET=0]
Calendar.DAY_OF_MONTH,1: java.util.GregorianCalendar[time=1478055252183,areFieldsSet=true,lenient=true,zone=America/Chicago,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2016,MONTH=10,WEEK_OF_YEAR=45,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=306,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=54,SECOND=12,MILLISECOND=183,ZONE_OFFSET=-21600000,DST_OFFSET=3600000]
Therefore, #skaffman Answer is not correct, as for your question Calendar.getTime(); indeed is needed if you do not want to get weird values at some point.
You could be hitting Bug ID 4851640
Calling get(...) / getTime() on a Calendar instance makes isSet(...) useless!
No, this is not true.
No, it should not be necessary.
Was the Calendar serialized immediate afterwards?
I've been caught by a bug with Calendar serialization in older jvms.
Bug parade bug #4328747
Calling getTime before serialization may be enough to get around the bug, although I don't have a sufficiently old JVM installed for me to confirm that.
Related
This question already has answers here:
Java Calendar adds a random number of milliseconds?
(4 answers)
Closed 4 years ago.
I'm wondering why I always get a difference between this date in milliseconds.
Any idea ?
Here is the output :
date = 1572794103293 ms
date2 = 1572794103341 ms
date3 = 1572794103341 ms
date4 = 1572794103341 ms
and here is the code :
Date date = createDate();
Date date2 = createDate();
Date date3 = createDate();
Date date4 = createDate();
System.out.println(date.getTime());
System.out.println(date2.getTime());
System.out.println(date3.getTime());
System.out.println(date4.getTime());
private static Date createDate() {
Calendar c = GregorianCalendar.getInstance();
c.set(2019, Calendar.NOVEMBER, 03, 16, 15, 03);
return c.getTime();
}
In the documentation of Calendar.set, it is said :
Sets the values for the fields YEAR, MONTH, DAY_OF_MONTH, HOUR, MINUTE, and SECOND. Previous values of other fields are retained. If this is not desired, call clear() first.
The reason is that not all fields are set with this method, in you case, you don't have MILLISECOND set. So it keep the value when the instance was created.
The call of Calendar.clear will
Sets all the calendar field values and the time value (millisecond offset from the Epoch) of this Calendar undefined.
A quick example :
Calendar c = GregorianCalendar.getInstance();
c.clear();
c.set(2019, Calendar.NOVEMBER, 03, 16, 15, 03);
System.out.println(c.getTimeInMillis());
1572794103000
Milliseconds being undefined will give 0
In addition to the comments and AxelH's answer mentioning the fact that the milliseconds of a Calendar instance aren't changed by Calendar.set, there is still the curiosity that you get the same value for date2, date3 and date4, but a different value for date.
This is because the very first time you call createDate() the JVM has to initialize the Date class, which happens after Calendar c was initialized.
Thus on the first call c.getTime() needs more time than on the consecutive calls, which you can see as the difference between the value of date and the other 3 instances.
If you add a call to new Date() before the first call to createDate(), the difference between each value should be the same.
Please note that this does not fix your issue, it just hides it if your machine is fast enough. It's merely an explanation for the particular values you get.
I am facing a weird behavior of java.util.Calendar.
The problem is when I add a method call Calendar#getTime() in between only than I get correct result but when I directly get the Dates of the week without calling Calendar#getTime() it refers to the next week instead of current week.
Please consider following code snippet :
public class GetDatesOfWeek {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.set(1991, Calendar.DECEMBER, 11);
//System.out.println(cal.getTime());//LINE NO : 14
for(int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) {
cal.set(Calendar.DAY_OF_WEEK, i);
Date date = cal.getTime();
System.out.println(sdf.format(date));
}
}
}
When I uncomment the line no 14 I get following output :
Wed Dec 11 07:38:06 IST 1991
08-12-1991
09-12-1991
10-12-1991
11-12-1991
12-12-1991
13-12-1991
14-12-1991
But when I comment that line and execute the code I get following output.
15-12-1991
16-12-1991
17-12-1991
18-12-1991
19-12-1991
20-12-1991
21-12-1991
Note that in both the cases month and year fields are proper but the start date changed from 08-12-1991 to 15-12-1991 for me 08-12-1991 is correct.
My Question :
Why I am getting different dates of the week in the above two cases ?
Why this kind of functionality is provided in Java ?
If you step through your code in a debugger, you will see interesting things happen to the internal variables of the cal object.
The calendar object stores both the time it represents and adjustment fields separately. After executing line 12, the cal object is constructed with the current time and no adjustment fields, and its internal variable isTimeSet is set to true. This means that the internal time stored is correct.
Executing line 13 clears isTimeSet to false because now the internal time needs to be adjusted by the adjustment fields before it is accurate again. This doesn't happen immediately, rather it waits for a call to getTime() or get(...), getTimeInMillis(), add(...) or roll(...).
Line 14 (if uncommented) forces the internal time to be recalculated using the adjustment fields, and sets the isTimeSet variable to true again.
Line 17 then sets another adjustment field, and unsets the isTimeSet variable again.
Line 18 recalculates the correct time again, based on the adjustment field set in line 17.
The solution:
The problem occurs when you combine setting the day-of-month with the day-of-week. When the day-of-week is set, the day-of-month setting is ignored, and the current day-of-month in the cal object is used as a starting point. You happen to be getting a week starting on the 15th because today's date is the 12th and 15th Dec 1991 is the nearest Sunday to 12th Dec 1991.
Note: If you run your test again in a week's time, you will get a different result.
The solution is to call getTimeInMillis() or getTime() to force recalculation of the time before setting day-of-week adjustments.
Testing:
If you don't want to wait a week to test again, try the following:
public class GetDatesOfWeek {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.set(2015, Calendar.AUGUST, 1); // adjust this date and see what happens
cal.getTime();
cal.set(1991, Calendar.DECEMBER, 11);
//System.out.println(cal.getTime());//LINE NO : 14
for(int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) {
cal.set(Calendar.DAY_OF_WEEK, i);
Date date = cal.getTime();
System.out.println(sdf.format(date));
}
}
}
My program needs to represent this date as a java.sql.date object , but it seems that when I create a new date (using the calendar) and set it to '9999-12-31' and finally convert this java.util.date object to a java.sql.date object, this date is converted to something like '000-01-31'.
Calendar calendar = Calendar.getInstance();
calendar.set(9999, 12, 31);
infinityDate = new java.sql.Date(normalizeDate(calendar.getTime()).getTime());
infinityDate should be 31-12-9999
but when my code reaches here :
if(otherDate.equals(infinityDate))
{// Do stuff}
It never goes into the if condition as the infinityDate has for some reason been changed to 31-01-000, even though otherDate is infact '31-12-9999'.
The fact that otherDate is 31-12-9999 tells me that java can represent this dates , but for some reason , when I construct it using a calendar it changes the date. (otherDate comes from a jdbc statement which fetches data from a database)
This reference date '31-12-9999' has been fixed by some client , so it cannot be changed and my program has to be able to compare some incoming date values with this.
Does anyone know why this is happening , I realize that http://en.wikipedia.org/wiki/Year_10,000_problem may be a problem for dates after year 9999 , but I should be safe by a day.
EDIT : The Normalize date method only "normalizes the given date to midnight of that day"
private static java.util.Date normalizeDate(java.util.Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
date = calendar.getTime();
return date;
}
But , this issue was appearing before I was normalizing the date , I normalized it in an attempt to fix this.
Months are zero indexed. Use 11 for December, not 12. This is why you are rolling over the year.
Calendar.MONTH is zero-based. The call
calendar.set(9999, 12, 31);
sets the date to "the 31st day in the 13th month of the year 9999", which is then implicitly converted to the 1st month of the year 10000. It would result in an exception if you first called
calendar.setLenient(false);
Check hours, minutes, seconds and milliseconds that are held into these 2 date objects. I believe they are different.
If your want to compare the date (year, month, day) only you should probably create your custom Comparator and use it.
This is a really simple request, but I am not quite sure the easiest/most efficient way of generating these two values.
I need to write a script that will check whether a given value is between two values. I am well aware of how this is done in SQL.
The way I need the values is somethign similar to the following.
Date testValue = new Date() //This represents the value we are testing
Date beginningOfDay = .... //This value would represent the date for
testValue at 12:00am
Date endOfDay = ... //This value would represent the date for
testValue at 11:59:59pm
Again, the Java Date() type may not be the best practice to do something like this. In the end I just need to generate three values that I can say
if testValue is after beginningOfDay && testValue is before endOfDay
//do logic
Personally I use the Calendar object for this. For example:
Date testDate = ??? //Replace with whatever source you are using
Calendar testDateCalendar = Calendar.getInstance();
testDateCalendar.setTime(testDate);
Date today = new Date();
Calendar endOfDay = Calendar.getInstance(); //Initiates to current time
endOfDay.setTime(today);
endOfDay.set(Calendar.HOUR_OF_DAY, 23);
endOfDay.set(Calendar.MINUTE, 59);
endOfDay.set(Calendar.SECOND, 59);
Calendar startOfDay = Calendar.getInstance();
startOfDay.setTime(today);
startOfDay.set(Calendar.HOUR_OF_DAY, 0);
startOfDay.set(Calendar.MINUTE, 0);
startOfDay.set(Calendar.SECOND, 0);
if (startOfDay.before(testDateCalendar) && endOfDay.after(testDateCalendar))
{
//Whatever
} else {
//Failure
}
You can use a calendar object to do this and by the way, the way you did the bounds check in your question is wrong (your date can match the before/after dates and still be considered in range). The following shows whether a date falls on a certain day of the year. It assumes that the timezones for the dateTime to check and the day are equal and that no time adjustments took place:
Date dateTime=...
Date day=...
// This is the date we're going to do a range check on
Calendar calDateTime=Calendar.getInstance();
calDateTime.setTime(dateTime);
// This is the day from which we will get the month/day/year to which
// we will compare it
Calendar calDay=Calendar.getInstance();
calDay.setTime(day);
// Calculate the start of day time
Calendar beginningOfDay=Calendar.getInstance();
beginningOfDay.set(calDay.Get(Calendar.YEAR),
calDay.Get(Calendar.MONTH),
calDay.Get(Calendar.DAY_OF_MONTH),
0, // hours
0, // minutes
0); // seconds
// Calculate the end of day time
Calendar endOfDay=Calendar.getInstance();
endOfDay.set(calDay.Get(Calendar.YEAR),
calDay.Get(Calendar.MONTH),
calDay.Get(Calendar.DAY_OF_MONTH),
23, // hours
59, // minutes
59); // seconds
// Now, to test your date.
// Note: You forgot about the possibility of your test date matching either
// the beginning of the day or the end of the day. The accepted answer
// got this range check wrong, as well.
if ((beginningOfDay.before(calDateTime) && endOfDay.after(calDateTime)) ||
beginningOfDay.equals(calDateTime) || endOfDay.equals(calDateTime))
{
// Date is in range...
}
This can be further simplified to:
Date dateTime=...
Date day=...
// This is the date we're going to do a range check on
Calendar calDateTime=Calendar.getInstance();
calDateTime.setTime(dateTime);
// This is the day from which we will get the month/day/year to which
// we will compare it
Calendar calDay=Calendar.getInstance();
calDay.setTime(day);
if (calDateTime.get(YEAR)==calDay.get(YEAR) &&
calDateTime.get(MONTH)==calDay.get(MONTH) &&
calDateTime.get(DAY_OF_YEAR)==calDay.get(DAY_OF_YEAR))
{
// Date is in range
}
Here's something I've used in my own code to determine if a file was modified on a certain day. Like the other answers in this thread, I used the Calendar.
// Get modified date of the current file
// and today's date
Calendar today = Calendar.getInstance();
Calendar modDate = Calendar.getInstance();
Date date = new Date(file.lastModified());
modDate.setTime(date);
// Convert dates to integers
int modDay = modDate.get(Calendar.DAY_OF_YEAR);
int todayDay = today.get(Calendar.DAY_OF_YEAR);
if (modDay == todayDay) {
// Do stuff
}
This might be closer to what you are looking for since you only need to see if the event falls on a certain day.
I have a program that needs to start on 1/1/09 and when I start a new day, my program will show the next day.
This is what I have so far:
GregorianCalendar startDate = new GregorianCalendar(2009, Calendar.JANUARY, 1);
SimpleDateFormat sdf = new SimpleDateFormat("d/M/yyyy");
public void setStart()
{
startDate.setLenient(false);
System.out.println(sdf.format(startDate.getTime()));
}
public void today()
{
newDay = startDate.add(5, 1);
System.out.println(newDay);
//I want to add a day to the start day and when I start another new day, I want to add another day to that.
}
I am getting the error found void but expected int, in 'newDay = startDate.add(5, 1);'
What should I do?
The Calendar object has an add method which allows one to add or subtract values of a specified field.
For example,
Calendar c = new GregorianCalendar(2009, Calendar.JANUARY, 1);
c.add(Calendar.DAY_OF_MONTH, 1);
The constants for specifying the field can be found in the "Field Summary" of the Calendar class.
Just for future reference, The Java API Specification contains a lot of helpful information about how to use the classes which are part of the Java API.
Update:
I am getting the error found void but
expected int, in 'newDay =
startDate.add(5, 1);' What should I
do?
The add method does not return anything, therefore, trying to assign the result of calling Calendar.add is not valid.
The compiler error indicates that one is trying to assign a void to a variable with the type of int. This is not valid, as one cannot assign "nothing" to an int variable.
Just a guess, but perhaps this may be what is trying to be achieved:
// Get a calendar which is set to a specified date.
Calendar calendar = new GregorianCalendar(2009, Calendar.JANUARY, 1);
// Get the current date representation of the calendar.
Date startDate = calendar.getTime();
// Increment the calendar's date by 1 day.
calendar.add(Calendar.DAY_OF_MONTH, 1);
// Get the current date representation of the calendar.
Date endDate = calendar.getTime();
System.out.println(startDate);
System.out.println(endDate);
Output:
Thu Jan 01 00:00:00 PST 2009
Fri Jan 02 00:00:00 PST 2009
What needs to be considered is what Calendar actually is.
A Calendar is not a representation of a date. It is a representation of a calendar, and where it is currently pointing at. In order to get a representation of where the calendar is pointing at at the moment, one should obtain a Date from the Calendar using the getTime method.
If you can swing it requirement wise, move all your date/time needs to JODA, which is a much better library, with the added bonus that almost everything is immutable, meaning multithreading comes in for free.