Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeZone issue in Java XMLGregorianCalendar

I hope this is not a repeat. I checked other searches here and all of them seem to talk about "displaying" the date in the right TimeZone format using SimpleDateFormat.

However, my problem is I obtain an XMLGregorianCalendar Object which is let us say in "CET".

I have to find out the format from this object and send the current time also in the same TimeZone as the server.

For eg: I need an XMLGregorianCalendar Object that returns me in this format(with Timezone):

2012-09-19T15:23:36.421+02:00

So I just tried this following snippet which seems to only return the time in local Timezone :(

TimeZone utc = TimeZone.getTimeZone("CET");
GregorianCalendar gc = new GregorianCalendar();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
df.setTimeZone(utc);
System.out.println(" - Gregorian UTC [" + df.format(gc.getTime()) + "]")

XMLGregorianCalendar currServTime = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);

System.out.println("currServTime is "+currServTime);
like image 612
user907810 Avatar asked Sep 19 '12 13:09

user907810


People also ask

How do I change the TimeZone in Java?

You can make use of the following DateFormat. SimpleDateFormat myDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); myDate. setTimeZone(TimeZone. getTimeZone("UTC")); Date newDate = myDate.

How do you show TimeZone in formatted date in Java?

Use "zzz" instead of "ZZZ": "Z" is the symbol for an RFC822 time zone. DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); Having said that, my standard advice on date/time stuff is to use Joda Time, which is an altogether better API.

What is Java default TimeZone?

According to javadoc the java. util. Date class represents number of milliseconds since the standard base time known as "the epoch", namely 1 January 1970, 00:00:00 GMT.

How do I change the TimeZone without changing the time in Java?

DateTimeZone timeZone = DateTimeZone. forID( "Australia/Sydney" ); String input = "2014-01-02T03:00:00"; // Note the lack of time zone offset at end. DateTime dateTime = new DateTime( input, timeZone );


1 Answers

You should include the time zone you're interested in in the GregorianCalendar, either by passing it to the constructor or by setting it afterwards. So either of these lines should work for you:

GregorianCalendar gc = new GregorianCalendar(utc);
gc.setTimeZone(utc);
like image 182
MvG Avatar answered Oct 02 '22 07:10

MvG