-1

I tried to convert the string date to UTC date with below Java code snippet but getting Unparseable date format exception. Please find the code below and help me fix this issue.

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm-SSSZ");
    String strDate= "2017-06-01T01:30-0400";
    try {
        Date date = formatter.parse(strDate);
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        date = new Date(formatter.format(date));
        System.out.println(date+"gmt");

    } catch (ParseException e) {
        e.printStackTrace();
    }

Thanks in advance.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
learner
  • 1,041
  • 3
  • 15
  • 31
  • 2
    I think it should be `yyyy-MM-dd'T'HH:mmZ`. There are no milliseconds in your string. – Phylogenesis Jun 01 '17 at 15:23
  • The `-0400` is the UTC offset, not the seconds, so your pattern should be `yyyy-MM-dd'T'HH:mmX` or `yyyy-MM-dd'T'HH:mmZ` –  Jun 01 '17 at 16:03
  • 3
    FYI, the `Date` & `SimpleDateFormat` classes are part of the troublesome old date-time classes, now legacy, supplanted by the java.time classes. `OffsetDateTime.parse( "2017-06-01T01:30-0400" ).toInstant()` Actually a tiny bug will bite when parsing that string with an offset-from-UTC lacking the optional colon character between hours and minutes. Either add the colon or define a formatting pattern with `DateTimeFormatter`. Bug fixed in Java 9. – Basil Bourque Jun 01 '17 at 16:51

1 Answers1

1

Cannot parse the

"yyyy-MM-dd'T'HH:mm-SSSZ"

Becuase of did not match with your

strDate= "2017-06-01T01:30-0400"

Try this:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm-SSS'Z'");
String strDate= "2017-06-01T01:30-040Z";
Blasanka
  • 21,001
  • 12
  • 102
  • 104
  • 3
    FYI, the `SimpleDateFormat` class is part of the troublesome old date-time classes, now legacy, supplanted by the java.time classes. `OffsetDateTime.parse( "2017-06-01T01:30-0400" )` – Basil Bourque Jun 01 '17 at 16:45
  • Oh thank you for mentioning. – Blasanka Jun 01 '17 at 16:48
  • 1
    Actually a tiny bug will bite when parsing that string with an offset-from-UTC lacking the optional colon character between hours and minutes. Either add the colon or define a formatting pattern. Bug fixed in Java 9. – Basil Bourque Jun 01 '17 at 16:50