I am using TimeZone.setDefault(TimeZone.getTimeZone("EST"));
to get the time zone EST and it is working fine to me. But sometimes I am getting time zone EDT when no one called this method in my project because of the default JVM time zone.
public getTimeInEST(XMLGregorianCalendar date) {
TimeZone.setDefault(TimeZone.getTimeZone("EST"));
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("EST"));
String newTime = formatter.format(date.toGregorianCalendar().getTime());
Date newDate = null;
try {
newDate = formatter.parse(newTime);
System.out.println("ESTDate : " + newDate)
} catch(ParseException e) {
System.out.println(e.getMessage);
}
}
Is there any other way where I get XMLGregorianCalendar date in EST time zone without using TimeZone.setDefault(TimeZone.getTimeZone("EST"))
?
I suspect you should just pass the time zone to toGregorianCalendar
. I'd also strongly recommend using full time zone IDs rather than abbreviations - after all, I suspect you really want Eastern time (EST and EDT) rather than just EST.
Also, there's no need to format a string value and then parse it - you can just use Calendar.getTime()
:
// Possibly...
public Date toDate(XMLGregorianCalendar date) {
TimeZone zone = TimeZone.getTimeZone("America/New_York");
Calendar calendar = date.toGregorianCalendar(zone, Locale.US, null);
return calendar.getTime();
}
Note that a Date
value doesn't have a time zone - it's just an instant in time. The return value of Date.toString()
is misleading in that it always uses the system default time zone, but there's no such thing as "a Date
in the Eastern time zone".
I've included the "possible" in the comment as it's not really clear what you're trying to achieve here. This code is only useful if the XMLGregorianCalendar
specifies the date/time but no time zone, and you want to assume it actually represents a value in the Eastern time zone, and convert that to an instant in time. Is that what you want?
See more on this question at Stackoverflow