user86834
user86834

Reputation: 5645

Java date offset format issue?

My date format is yyyy-MM-dd'T'HH:mm:ss.SSSZ, which is producing the date :

2013-10-08T12:14:39.721+0100

But I need the date to be :

2013-10-08T12:14:39.721+01:00

what date format will generate the offset with a colon?

Upvotes: 4

Views: 10495

Answers (4)

Basil Bourque
Basil Bourque

Reputation: 338496

tl;dr

OffsetDateTime.parse( "2013-10-08T12:14:39.721+01:00" )
              .toString()

2013-10-08T12:14:39.721+01:00

java.time

Use the modern java.time classes that supplant the troublesome legacy date-time classes.

Your desired output format happens to be the default of OffsetDateTime::toString method.

OffsetDateTime odt = OffsetDateTime.parse( "2013-10-08T12:14:39.721+01:00" ) ;
String output = odt.toString() ;

output: 2013-10-08T12:14:39.721+01:00

See this code run live at IdeOne.com.

By the way, in my experience is indeed best to format your offset-from-UTC as you asked in your Question: with the colon, with padding zero, and with both hours and minutes. While the ISO 8601 standard and others technically allow variations, I have found some libraries and protocols expect only the fully expanded format. So use +05:00 rather than +05 or +5:00 or +0500.

Upvotes: 1

Rahul
Rahul

Reputation: 45060

You can use this format

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

Have a look at the doc for more info.

P.S:- As my friend @Thomas mentioned, this will work only with Java 7 and above.

Upvotes: 10

Jayamohan
Jayamohan

Reputation: 12924

If you want to implement using SimpleDateFormat you can use R.J. solution which will work for JDK 7. You can also implement the same using Joda time as below

DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
String str = fmt.print(dt);
System.out.println(str);

which outputs,

2013-10-08T20:36:19.802+09:00

Upvotes: 1

Dropout
Dropout

Reputation: 13866

Changing it simply to that format doesn't work? Or you're unable to change the date format? Try:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSXXX");

It should return the last part separated by a colon.

See: Java SimpleDateFormat Timezone offset with minute separated by colon

Upvotes: 0

Related Questions