-1

I am looking to convert the date from default Date format to timestamp in Java. I tried the following code, but it doesn't work:

String string = "2017-08-01T16:00:00-04:00";
DateTimeFormatter formatter = 
                  DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss-mm:ss");
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);

java.time.format.DateTimeParseException: Text '2017-08-01T16:00:00-04:00' could not be parsed at index 20

at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) at java.time.LocalDate.parse(LocalDate.java:400)

ernest_k
  • 44,416
  • 5
  • 53
  • 99
Stranger95
  • 123
  • 1
  • 9

1 Answers1

4

Don't use a LocalDate for a String that

  1. contains information about the time of day, wich would have required a LocalDateTime and
  2. contains an offset, wich cannot be considered by a LocalDateTime.

Instead, use an OffsetDateTime:

public static void main(String[] args) {
    String string = "2017-08-01T16:00:00-04:00";
    OffsetDateTime odt = OffsetDateTime.parse(string);
    System.out.println(odt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
}

Output:

2017-08-01T16:00:00-04:00

In addition, your pattern in DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss-mm:ss"); has serious flaws, like duplicate items.

You can of course print the result using a pattern different from the input (which complies with the ISO 8601 standard):

public static void main(String[] args) {
    String string = "2017-08-01T16:00:00-04:00";
    OffsetDateTime odt = OffsetDateTime.parse(string);
    System.out.println(odt.format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss Z")));
}

Output this time:

01.08.2017 16:00:00 -0400
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
deHaar
  • 17,687
  • 10
  • 38
  • 51
  • 1
    I suggest printing in a format other than the input – OneCricketeer Jan 09 '20 at 15:30
  • @cricket_007 neat suggestion, thanks... Added a second example. – deHaar Jan 09 '20 at 15:35
  • @deHaar thanks for help. Could you also specify how to convert `OffsetDateTime` to timestamp correctly? – Stranger95 Jan 09 '20 at 15:45
  • 1
    @StanislavFedosov do you mean a `java.sql.Timestamp`? Or some representation like milliseconds? – deHaar Jan 09 '20 at 15:56
  • Have a look at [this question](https://stackoverflow.com/questions/30651210/convert-offsetdatetime-to-utc-timestamp)... – deHaar Jan 09 '20 at 16:19
  • An `OffsetDateTIme` *is* a timestamp in the sense that it represents a well-defined moment in time. If you had something else in mind when you said timestamp, please specify. We can probably provide what you want when we understand what. – Ole V.V. Jan 09 '20 at 19:02