Allen Sparks
Allen Sparks

Reputation: 15

Convert a String time to a localtime to compare

I am trying to figure out the math to verify shifts are getting correct breaks, when I query the api I get the following response:

    "StartDate": "4/25/2018",
    "EndTime": "8:30PM",
    "StartDayNumber": 1,
    "StartTime": "7:30PM",
    "SegmentTypeName": "BREAK",
    "EndDate": "4/25/2018",
    "EndDayNumber": 1

I have tried various attempts at using LocalTime so I can use the function Duration:

LocalTime start = LocalTime.parse(employeeShift.getJSONObject(ii).get("StartTime").toString(), DateTimeFormatter.ofPattern("HH:mm a"));
LocalTime end = LocalTime.parse(employeeShift.getJSONObject(ii).get("EndTime").toString());

I have tried various way to convert EndTime and StartTime to a local time. However I am stumped I have tried a various number of formatters including the day, the hour but I have not found an example that included the am/pm, do I need to convert to 24 hour time first?

The error I've got:

java.time.format.DateTimeParseException: Text '1:00PM' could not be parsed at index 0

Upvotes: 0

Views: 407

Answers (1)

user9700673
user9700673

Reputation: 38

You just need to fix your DateTimeFormatter. "HH" is the hour-of-day (values from 0 to 23). To parse AM/PM hours, you need to use "hh" (clock hour of am/pm, values from 1 to 12 - check the javadoc). Also, there's no space between the minutes and the AM/PM part, and to parse one digit hours, you can use just one "h" (it'll accept one or 2 digits, which seems to match your inputs):

LocalTime.parse("7:30PM", DateTimeFormatter.ofPattern("h:mma", Locale.US));

I also used a java.util.Locale because AM/PM strings are localized, and if I don't specify one, the JVM default will be used - although for most locales "AM" and "PM" are used, there are other languages that produces things like "a.m." or some other string.

Upvotes: 2

Related Questions