Reputation: 5645
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
Reputation: 338496
OffsetDateTime.parse( "2013-10-08T12:14:39.721+01:00" )
.toString()
2013-10-08T12:14:39.721+01:00
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
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
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
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