4

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?

user86834
  • 5,357
  • 10
  • 34
  • 47

4 Answers4

9

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.

Rahul
  • 44,383
  • 11
  • 84
  • 103
1

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
Community
  • 1
  • 1
Jayamohan
  • 12,734
  • 2
  • 27
  • 41
1

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

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

Community
  • 1
  • 1
Dropout
  • 13,653
  • 10
  • 56
  • 109