2

I'm trying to convert into HH:MM format in Java

Here is my code

String date = "18:30:00.000Z";

    try {
        ZonedDateTime parsed = ZonedDateTime.parse(date);

        ZonedDateTime z = parsed.withZoneSameInstant(ZoneId.systemDefault());

        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
        System.out.println(fmt.format(z));
    } catch(Exception e) {
        e.printStackTrace();
    }

Is there anything wrong in my code

Here is the exception

java.time.format.DateTimeParseException: Text '18:30:00.000Z' could not be parsed at index 0
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Syed
  • 2,471
  • 10
  • 49
  • 89
  • Could you provide the exception/error output? – ev350 Jan 16 '20 at 13:32
  • 3
    18:30:00.000Z isn't a `ZonedDateTime` - what would you expect the date to be? The closest type would be `OffsetTime` (with an offset of 0). Is it *always* going to be Z at the end though? If so, I'd probably trim that and parse as a LocalTime, then format with a different formatter. – Jon Skeet Jan 16 '20 at 13:44
  • 2
    `ZonedDateTime` expects an ISO-8601 style String, such as `2007-12-03T10:15:30+01:00 Europe/Paris`. [source](https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html) – RobCo Jan 16 '20 at 13:45
  • I'm expecting 18:30:00.000Z will return as 6:30PM – Syed Jan 16 '20 at 13:46
  • @JonSkeet, can you pls let me know what needs to be done, I'm expecting 18:30:00.000Z will return as 6:30PM – Syed Jan 16 '20 at 13:47
  • Why the jodatime tag? It seems inappropriate here. – Ole V.V. Jan 16 '20 at 17:40

1 Answers1

4

The string you are trying to parse is not a date and time, but only a time. So the type ZonedDateTime is not the appropriate type to use here. Use OffsetTime instead, which is a class for holding just a time (without a date).

String input = "18:30:00.000Z";
OffsetTime time = OffsetTime.parse(input);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm a");
String result = formatter.format(time);
System.out.println(result);

Output:

6:30 PM
Jesper
  • 202,709
  • 46
  • 318
  • 350
  • 1
    Simple and perfect. Thank you. – Syed Jan 16 '20 at 13:55
  • More precisely, as the name says, `OffsetTime` is for a time *with an offset from UTC*. The `Z` in your string means offset zero from UTC, so this is just perfect. – Ole V.V. Jan 16 '20 at 17:38