gpol
gpol

Reputation: 966

Java convert date to EST timezone to respecting DST

I want to get the current date converted to America/Montreal timezone. I'm doing it like this:

Date date = new Date();
TimeZone timeZone = TimeZone.getTimeZone ("America/Montreal");
Calendar cal = new GregorianCalendar(timeZone);
cal.setTime(date);
String whatIWant = "" + cal.get(Calendar.HOUR_OF_DAY) + ':'+ 
                   cal.get(Calendar.MINUTE)+ ':'+ cal.get(Calendar.SECOND);

log.info(whatIWant);

The conversion is just fine but I was wondering how robust this code is. What will happen when in no daylight saving?

Upvotes: 1

Views: 4825

Answers (1)

Jesper
Jesper

Reputation: 206836

That code is fine. Java automatically takes winter time or summer time into account.

You could also do this by using a DateFormat object to convert the date to a string, setting the desired time zone on the DateFormat object:

Date date = new Date();

DateFormat df = new SimpleDateFormat("HH:mm:ss");

// Tell the DateFormat that you want the time in this timezone
df.setTimeZone(TimeZone.getTimeZone("America/Montreal"));

String whatIWant = df.format(date);

Upvotes: 6

Related Questions