Andez Andez - 3 months ago 10
Java Question

Java Date (Calendar) calculating the start of a day in local time given a date time

All,

Having a hard day in the office with this one... I am trying to workout the start of a day in Local Time, i.e. Midnight 00:00:00, given any calendar date.

Given the following days, I want to calculate the start of the day at local time midnight:

Time Start Day (Local) Start Day (GMT)
2011-03-27 00:00:00 GMT --> 2011-03-27 00:00:00 GMT --> 2011-03-27 00:00:00 GMT
2011-03-27 01:00:00 GMT --> 2011-03-27 00:00:00 GMT --> 2011-03-27 00:00:00 GMT
2011-03-27 02:00:00 GMT --> 2011-03-27 00:00:00 GMT --> 2011-03-27 00:00:00 GMT
2011-04-01 00:00:00 BST --> 2011-04-01 00:00:00 BST --> 2011-03-31 23:00:00 GMT
2011-10-30 00:00:00 BST --> 2011-10-30 00:00:00 BST --> 2011-10-29 23:00:00 GMT
2011-10-30 01:00:00 BST --> 2011-10-30 00:00:00 BST --> 2011-10-29 23:00:00 GMT
2011-10-30 01:00:00 GMT --> 2011-10-30 00:00:00 BST --> 2011-10-29 23:00:00 GMT
2011-11-01 00:00:00 GMT --> 2011-11-01 00:00:00 GMT --> 2011-11-01 00:00:00 GMT


At present, I am parsing the String Time into a GregorianCalendar using a SimpleDateFormat. This gives me the GMT/UTC time to calculate from.

So I have some code which parses the string into a GregorianCalendar:

public GregorianCalendar getCalendar(String dateTime) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(sdf.parse(dateTime, new ParsePosition(0)));

return cal;
}


Now I need to set it to midnight locally:

public void setToStartOfDayLocally(GregorianCalendar cal) {
????
}


I am not too sure what I need to do at the minute with the Calendar. Unfortunately we are not moving to JODA date in the near future. I am also not accounting for different time zones with my example.

Any thoughts?

Thanks,

Andez

Answer

I think this code might solve your issue. I am using it to convert from time in local timezone to another.

public static Date convertLocalDateToDateTimezone( Date localDate, String timezone ) {
   TimeZone localTimeZone = TimeZone.getDefault();
   TimeZone timezone = TimeZone.getTimeZone( timezone );
   long gmtMillis = localDate.getTime();
   long result = gmtMillis + timezone.getOffset( gmtMillis ) - localTimeZone.getOffset(     gmtMillis );
   return new Date( result );
}

Hope this helps.