'Converting string to Instant

I am trying to covert datetime in string to instant using java 8 or utils package.

For eg.

String requestTime = "04:30 PM, Sat 5/12/2018";

to

Instant reqInstant should result in 2018-05-12T20:30:00.000Z

reqString is in America/Toronto timezone.

This is what I tried

 String strReqDelTime = "04:30 PM, Sat 5/12/2018";
 Date date = new SimpleDateFormat("hh:mm a, EEE MM/dd/yyyy").parse(requestTime);
 Instant reqInstant = date.toInstant();

The above code results in "2018-05-12T23:30:00Z".

Any help is appreciated.



Solution 1:[1]

It seems like Time Zone in your computer(server) is US Pacific DST (GMT-7), but you expect to have result for US Eastern DST (GMT-4).

Instant.toString() returns UTC (GMT+0) DateTime in ISO-8601 format. ('Z' at the end means UTC).

SimpleDateFormat treats DateTime String in default Time Zone of computer when it is not specified. And your input does not specify time zone.

So, you need to do something about in what time zone your input is.

PS. on mine machine in Eastern DST your code gives me result exactly as you expected.

Solution 2:[2]

For the description you can read here [https://www.baeldung.com/java-string-to-date]

String requestTime = "04:30 PM, Sat 5/12/2018 America/Toronto";
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm a, EEE M/dd/yyyy z");
            ZonedDateTime zonedDateTime = ZonedDateTime.parse(requestTime, formatter);
            System.out.println(zonedDateTime.toInstant());  

Solution 3:[3]

Instant.parse(String) appropriately formatted

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Upperstage
Solution 2 shila mosammami
Solution 3 Andrea Paolo Ferraresi