2

INPUT:

SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

String unformattedDate = "2013-11-16T08:46:00.000-06:00";

String formattedDate = outFormat.format(inFormat.parse(unformattedDate ));

ABOVE OUTPUT:

formattedDate = "2013-11-16T20:16:00.000Z"

DESIRED OUTPUT:

formattedDate = "2013-11-16T08:46:00.000Z"

Can anyone through a light on why is this difference after conversion and how to get the desired output?

I assume that my inFormat is not correct to format the date unformattedDate.

sjain
  • 23,126
  • 28
  • 107
  • 185

1 Answers1

2

do like this

 String unformattedDate = "2013-11-16T08:46:00.000-06:00";
 Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(unformattedDate);
 String formattedDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(date);
 System.out.println(formattedDate);

output

2013-11-16T08:46:00.000Z
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
  • Great! But how come the second line not giving parse exception as the format of `unformattedDate` is different then "yyyy-MM-dd'T'HH:mm:ss" and we are parsing it in second line? – sjain Dec 03 '13 at 15:28
  • its because his date format is ignoring the malformatted timezone string. IN the spec the time zone is referenced without a colon `-0600` – nsfyn55 Dec 03 '13 at 15:37
  • checkout this http://stackoverflow.com/questions/2375222/java-simpledateformat-for-time-zone-with-a-colon-seperator – nsfyn55 Dec 03 '13 at 15:38