Date to Day conversion in Java

GKD picture GKD · Oct 31, 2011 · Viewed 9.3k times · Source

I am able to convert date to days using the below code.

 SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd");
 String s1 = sfd.format(dateObj);
 String a1 [] = s1.split("-");
 int year = Integer.parseInt(a1[0].toString());
 int month = Integer.parseInt(a1[1])-1;
 int day = Integer.parseInt((a1[2]));

 Calendar c1 = Calendar.getInstance();
 c1.set(year,month,day);

 days = c1.getTime().getTime()/(24*60*60*1000);

The above code works accurately in my system which is windows with timezone GMT +5.30.

However the same code in EST or Pacific timezone adds a day by 1 to final result when the time is 20.00 in the system.

What could be the issue ?

Do we need to set Timezone explicitly in the code ?

input dates does not hold any time stamp .. is it correct to store in java.util.Date instead of java.sql.Date?

Answer

Jon Skeet picture Jon Skeet · Oct 31, 2011

EDIT: As per Alex's comment, it's possible that the problems with the start of your code have blinded me to your real aim.

A Date represents an instant in time. That can fall on different dates depending on the time zone, but how do you want that to affect things? Do you want the number of days since the Unix epoch (which is always UTC) or the number of days since the 1st January 1970 in a particular time zone? Why do you want this "number of days" instead of a representation of a date such as LocalDate? What's the use case here?

EDIT: If you just want to know the number of days since the Unix epoch, you can skip most of this:

days = dateObj.getTime() / (24 * 60 * 60 * 1000);

You shouldn't be going through formatting at all just to get the year / month / day. Just create a Calendar, set the relevant time zone, call setTime with the dateObj you've already got, and then clear the hour/minute/second part of the calendar.

However, you should explicitly specify which time zone you want to consider - a Date represents an instant in time, which will mean different dates in different time zones.

You should also consider using Joda Time which makes all of this simpler and has a specific type for dates (LocalDate). That would also make it easy to find the number of days between the Unix epoch and a particular date without performing the division yourself.