Gregorian calendar midnight time not giving a round number - java

This code snippet
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
cal.set(2013, Calendar.NOVEMBER, 6, 0, 0, 0);
long time = cal.getTimeInMillis();
results in time == 1383696000628.
Where the heck is it getting those last 628 milliseconds from?
I'm using Java 6.

Calendar.set(int year, int month, int date, int hourOfDay, int minute, int second) does not change MILLISECOND field, its API says
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.

cal.set(int, int, int, int, int, int) does not set the milliseconds.
Therefore, the Calendar instance still contains the milliseconds from its creation time.
You can use GregorianCalendar(int year, int month, int dayOfMonth), although you would loose the locale, or cal.set(Calendar.MILLISECOND, 0) to remove the millis.
Edit
As suggested by Jonathan Drapeau in the comment below, you can also call cal.clear() to remove all fields before calling set

Related

Statically created dates are not equal?

I'm testing the equality of dates that I create using constants and for some reason the tests are all failing.
public static Date date(int year, int month, int date, int hour, int minute) {
Calendar working = GregorianCalendar.getInstance();
working.set(year, month, date, hour, minute, 1);
return working.getTime();
}
If I create that with the same year, month, date, hour etc then I expect it to be equal. Except that it inconsistantly isn't. I use this function in two different classes and the objects aren't equal - except only sometimes.
What's the issue? The epoch it gives me is occasionally 1 second behind the other and I'm not entirely sure why.
getTime is millisecond precision, you are only setting to second precision. So when you compare the Dates using the .equals() method it will return false.
Stop using the abomination of the java date time api and use jodatime instead.
DateTime dateTime = new DateTime().secOfDay().roundFloorCopy();
dateTime.equals(myOtherDateTimeCreatedSameway);
Or if you are just worried about date, not time, use LocalDate.
The old calendar-API is undoubtedly horrible in general but I show a possible solution which suppresses the millisecond part generated in constructor. This will work as long as you don't change the timezone. So sometimes the Calendar-API is underestimated while JodaTime is often overestimated.
public static Date date(int year, int month, int date, int hour, int minute) {
// current time in system timezone
GregorianCalendar working = new GregorianCalendar();
// assuming you rather want second set to zero
working.set(year, month, date, hour, minute, 0);
// no millisecond part
working.set(Calendar.MILLISECOND, 0);
return working.getTime();
}

Android get difference in milliseconds between two dates

I have Integer fields:
currentYear,currentMonth,currentDay,currentHour,currentMinute and nextYear,nextMonth,nextDay,nextHour,nextMinute.
How I can get difference between those two spots in time in milliseconds.
I found a way using Date() object, but those functions seems to be depricated, so it's little risky.
Any other way?
Use GregorianCalendar to create the date, and take the diff as you otherwise would.
GregorianCalendar currentDay=new GregorianCalendar (currentYear,currentMonth,currentDay,currentHour,currentMinute,0);
GregorianCalendar nextDay=new GregorianCalendar (nextYear,nextMonth,nextDay,nextHour,nextMinute,0);
diff_in_ms=nextDay. getTimeInMillis()-currentDay. getTimeInMillis();
Create a Calendar object for currenDay and nextDay, turn them into longs, then subtract. For example:
Calendar currentDate = Calendar.getInstance();
Calendar.set(Calendar.MONTH, currentMonth - 1); // January is 0, Feb is 1, etc.
Calendar.set(Calendar.DATE, currentDay);
// set the year, hour, minute, second, and millisecond
long currentDateInMillis = currentDate.getTimeInMillis();
Calendar nextDate = Calendar.getInstance();
// set the month, date, year, hour, minute, second, and millisecond
long nextDateInMillis = nextDate.getTimeInMillis();
return nextDateInMillis - currentDateInMillis; // this is what you want
If you don't like the confusion around the Calendar class, you can check out the Joda time library.

Date picking and finding difference

I am a novice to Java programming using Netbeans. I have added jCalendar to my GUI to pick a date.
I have entered this line in Events -> "property change" code of jCalendar button,
Date date=jcalendar1.getDate();
So that I get the date immediately when it is changed. Am I right?
The purpose:
I want to find the difference in milliseconds from the afternoon (12:00 pm) of this date above to NOW (current date and time).
There are several programs showing the date difference but all have dates hardcoded and being a newbie i do not know how to replace it with the date that is picked. (also i am confused between the objects Date and Calendar, not able to understand the difference between them). For example, a piece from here:
http://www.java2s.com/Code/Java/Data-type/ReturnsaDatesetjusttoNoontotheclosestpossiblemillisecondoftheday.htm
if (day == null) day = new Date();
cal.setTime(day);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
return cal.getTime();
Here day is a Date object. How is cal (a calendar object) linked to it to enter the time. How should the cal object be defined first? How can I use this or anything else in your opinion for my program. A piece of code with detail comments will be more helpful
thanks!
Instead of using :
Date day = new Date();
Use:
Calendar cal = Calendar.getInstance();
cal.set (...);
Date date = new Date(cal.getTimeInMillis());
Worth abstracting this stuff out to a DateUtils class or similar, with something like the following:
public static Date create(int year, int month, int day, int hour, int minute, int second) {
return new Date(getTimeInMillis(year, month, day, hour, minute, second));
}
public static long getTimeInMillis(int year, int month, int day, int hour, int minute, int second, int milliseconds) {
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(year, month, day, hour, minute, second);
cal.set(Calendar.MILLISECOND, milliseconds);
return cal.getTimeInMillis();
}

Problems with the Date 31-12-9999 in java

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.

In java, Date() method returns a value. but I am confused in that

I used Date() for getting the date of my birthday, but it was returned the mismatch of the month. My birthday is 04-March-87. so i gave an input as,
Date birthDay= new Date(87,03,04,8,30,00);
But it returns correct year, day and time. But month was problem. It displays April month.
What's wrong with that?
Months are set from 0 to 11, January =0, February = 1, ..., December = 11.
So, for April do this:
Date birthDate = new Date(87,02,04,8,30,00); //March = 2
Hope this helps;
EDIT
The Date class with this constructor public Date(int year, int month, int date, int hrs, int min) is deprecated (i.e. it has been declared #Deprecated).
Rather do this.
Calendar calendar = Calendar.getInstance();
Calendar.set(1987, 2, 4, 0, 0, 0);
Date birthDate = calendar.getTime();
(It will return the same thing as what you asked for)
The month in the Date class starts with 0 for January, so March is 2, not 3.
Also, the Date(int, int, int, int, int, int) constructor is deprecated, so you should consider using the Calendar class instead.
Finally, be careful with leading zeros in Java - they represent octal constants. The number 09 would not do what you expect.

Categories