Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Datetime with Timezone format

I am currently using SimpleDateFormat to create a datetime value in the format yyyy-MM-dd HH:mm:ss. Here is my code:

     Date date = new SimpleDateFormat("yy-M-d H:m:ss").parse(datetime);
     String Dtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);

However I would like the format to be this instead:

  2013-04-12T13:38:48+02:00

How can I add the timezone to get the desired format?

Thank you!

like image 900
diego10 Avatar asked Apr 12 '13 11:04

diego10


People also ask

How do you specify TimeZone in date format?

SimpleDateFormat myDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); myDate. setTimeZone(TimeZone. getTimeZone("UTC")); Date newDate = myDate. parse("2010-05-23T09:01:02");

Does Java date have TimeZone?

The java. util. Date has no concept of time zone, and only represents the number of seconds passed since the Unix epoch time – 1970-01-01T00:00:00Z. But, if you print the Date object directly, the Date object will be always printed with the default system time zone.

How do you add time zones in Java?

Using Java 7 First, let's get the current UTC date and a TimeZone object: Date nowUtc = new Date(); TimeZone asiaSingapore = TimeZone. getTimeZone(timeZone); In Java 7, we need to use the Calendar class to represent a date with a time zone.


1 Answers

Have a look at the API documentation of SimpleDateFormat. There you can see, that you can use the character 'z' for the timezone information.

Example: "yyyy.MM.dd G 'at' HH:mm:ss z" will give you "2001.07.04 AD at 12:08:56 PDT"

To set the timezone on a date have a look at this question and the answers.

like image 52
thalador Avatar answered Nov 01 '22 07:11

thalador