0

I need to convert date string into a another specific format.

For example: I've a date which can come as YYYY-MM-DD or YYYY-MM-DDThh:mm:ss±0000 and I need to convert that to something "yyyy-mm-ddTHH:MM:SSZ".

I tried few things using Java 8 API but could not find a way out.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
User5817351
  • 989
  • 2
  • 16
  • 36
  • 1
    Please give some example inputs and outputs. – James Monger Oct 14 '16 at 18:03
  • 1
    can you put your code which have issues? – Ammad Oct 14 '16 at 18:10
  • 1
    Here is general solution: [How do I convert the date from one format to another date object in another format without using any deprecated classes?](http://stackoverflow.com/a/12503542). Now try to specify what problem exactly is stopping you from using it. Do you get compilation errors, runtime exceptions, incorrect results, or some other problems? – Pshemo Oct 14 '16 at 18:16

2 Answers2

5

Try this (Java 8):

String input = "2016-10-14T14:19:40-04:00";
String output = ZonedDateTime.parse(input).toInstant().toString();
System.out.println(output); // prints 2016-10-14T18:19:40Z

This works because the primary format of ZonedDateTime used by parse() is ISO_ZONED_DATE_TIME, so it will parse input in the format you described.

The output format you requested happens to be the default format of Instant, as returned by its toString() method, i.e. the ISO_INSTANT format.

Converting between the two (ZonedDateTime to Instant using the toInstant() method) will perform the timezone adjustment necessary.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • 1
    Good answer, but more appropriate to use `OffsetDateTime` rather than `ZonedDateTime` for input that only has offset and no time zone info. – Basil Bourque Oct 14 '16 at 21:57
0

Try this:

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd"); // or "YYYY-MM-DDThh:mm:ss±0000"
String dateInString = "1993-11-27";
Date date = inputFormat.parse(dateInString);

SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ssZ");
System.out.println(outputFormat.format(date));
SpiralDev
  • 7,011
  • 5
  • 28
  • 42
  • 1
    This Answer uses troublesome old date-time classes now supplanted by the java.time classes. See the [Answer by Andreas](http://stackoverflow.com/a/40049730/642706) for the modern solution. – Basil Bourque Oct 14 '16 at 21:59