Java 8+
You could also use the newer Time API in Java 8, something like...
String formatIn = "yyyy-MM-dd-HH.mm.ss.SSSSSS";
String formatOut = "yyyy-MM-dd'T'HH:mm:ss.SSSz";
String valueIn = "2016-01-19-09.55.00.000000";
LocalDateTime ldt = LocalDateTime.parse(valueIn, DateTimeFormatter.ofPattern(formatIn));
System.out.println("< " + ldt);
ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());
String out = DateTimeFormatter.ofPattern(formatOut).format(zdt);
System.out.println("> " + out);
Which outputs...
< 2016-01-19T09:55
> 2016-01-19T09:55:00.000AEDT
This makes you far more responsible for managing the time zones which might be a better solution generally
And because converting between time zones in the Java 8 API gives me a headache (lack of experience :P)
LocalDateTime ldt = LocalDateTime.parse(valueIn, DateTimeFormatter.ofPattern(formatIn));
System.out.println("< " + ldt);
ZonedDateTime here = ldt.atZone(ZoneId.systemDefault());
System.out.println("here " + here);
ZonedDateTime there = here.withZoneSameInstant(ZoneId.of("GMT"));
System.out.println("there " + there);
String out = DateTimeFormatter.ofPattern(formatOut).format(there);
System.out.println("> " + out);
Which outputs...
< 2016-01-19T09:55
here 2016-01-19T09:55+11:00[Australia/Sydney]
there 2016-01-18T22:55Z[GMT]
> 2016-01-18T22:55:00.000GMT
FYI: I think your input is using nano/micro seconds and not milliseconds (there's only 1000 milliseconds in a second). SimpleDateFormat
does not support nano/micro seconds, but DateTimeFormatter
does, you'd have to use the n
pattern, yyyy-MM-dd-HH.mm.ss.nnnnnn
for example
Java 7 and below
The basic answer is, use a SimpleDateFormat
....
String formatIn = "yyyy-MM-dd-HH.mm.ss.SSSSSS";
String formatOut = "yyyy-MM-dd'T'HH:mm:ss.SSSz";
String valueIn = "2016-01-19-09.55.00.000000";
SimpleDateFormat in = new SimpleDateFormat(formatIn);
SimpleDateFormat out = new SimpleDateFormat(formatOut);
Date dateIn = in.parse(valueIn);
System.out.println("< " + dateIn);
String valueOut = out.format(dateIn);
System.out.println("> " + valueOut);
Which outputs...
< Tue Jan 19 09:55:00 AEDT 2016
> 2016-01-19T09:55:00.000AEDT
The problem here is, you could be converting across different time zones, which case, you could use something like...
in.setTimeZone(TimeZone.getTimeZone("GMT"));
dateIn = in.parse(valueIn);
System.out.println("< " + dateIn);
out.setTimeZone(TimeZone.getTimeZone("GMT"));
valueOut = out.format(dateIn);
System.out.println("> " + valueOut);
which outputs
< Tue Jan 19 20:55:00 AEDT 2016
> 2016-01-19T09:55:00.000GMT
or a combination of, if you want to covert to a different time zone.
But, personally, I'd use Joda-Time, but that's me