Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

Gooey picture Gooey · Mar 31, 2013 · Viewed 324k times · Source

I'm trying to format a date in yyyy-MM-dd'T'HH:mm:ss.SSSz format to yyyy-mm-dd HH:mm:ss, which should be easy but I can't get it to work.

A date that has to be parsed is in the form of: 2012-10-01T09:45:00.000+02:00
Now i use this simple date formatter to format it:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz", Locale.FRANCE);

yet this gives an output similar to 2012-10-01T09:45:00.000UTC+00:00.

I've also tried to use "yyyy-MM-dd'T'HH:mm:ss.SSSZ" as pattern and "yyyy-MM-ddHH:mm:ss". The latter returns a date in the form of 2012-10-01T09:45:00 close, but not there yet.

I figured substringing the T away would be a bit messy and creates overhead for no reason, thus what would be the proper way to format these dates?

To illustrate I would like to convert 2012-10-01T09:45:00.000+02:00 into 2012-10-01 09:45:00

Cheers!

Answer

ctlevi picture ctlevi · Mar 31, 2013
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse(time);
String formattedTime = output.format(d);

This works. You have to use two SimpleDateFormats, one for input and one for output, but it will give you just what you are wanting.