9

I have a datetime-string WITHOUT a specified timezone. But I want to parse it with ZonedDateTime to give it a timezone-meaning in the act of parsing.

This code is working but uses LocalDateTime for parsing - and then convert it to ZonedDateTime with giving it a timezone-meaning.

DateTimeFormatter dtf = DateTimeFormatter.ofPattern ("yyyyMMddHHmm");

String tmstr = "201810110907";

LocalDateTime tmp = LocalDateTime.parse (tnstr,dtf);
ZonedDateTime mytime = ZonedDateTime.of (tmp, ZoneId.of ("UTC"));

Is there a way I can parse it directly with ZonedDateTime?

I have tried this, but it was not working.

mytime = mytime.withZoneSameInstant(ZoneId.of("UTC")).parse(str,dtf);
chris01
  • 10,921
  • 9
  • 54
  • 93
  • You already know the format... what's stopping you for just appending a string with the correct timezone you want to the raw date string? – Tschallacka Jun 28 '18 at 12:35
  • By the way, I suggest educating the publisher of your data about the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. The format seen in your Question is close to complying with the “Basic” variation in the standard format for a date-with-time. To fully comply, insert a `T` between the date portion and the time-of-day portion: `"20181011T0907"`. Even better used the expanded variation, also used by default in the *java.time* classes: `"2018-10-11T09:07"`. And if the date with time was intended to be regarded as in UTC, then say so by appending a `Z` on the end: `"2018-10-11T09:07Z"`. – Basil Bourque Feb 05 '20 at 23:08

1 Answers1

13

You may specify a default time zone on the formatter:

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmm")
            .withZone(ZoneId.of("UTC"));
    String tmstr = "201810110907";
    ZonedDateTime mytime = ZonedDateTime.parse(tmstr, dtf);
    System.out.println(mytime);

Output:

2018-10-11T09:07Z[UTC]

Bonus tip: Rather than ZoneId.of("UTC") it’s usually nicer to use ZoneOffset.UTC. If you accept the output being printed as 2018-10-11T09:07Z instead (Z meaning UTC).

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • This doesn't work as soon as I make `HHmm` optional and don't supply a time it in the string. Any idea how to solve that? – Mark Jeronimus Apr 09 '20 at 13:00
  • @MarkJeronimus Then you need to use a `DateTimeFormatterBuilder` and use its `parseDefaulting` method for specifying which time of day you want if it's not in the string. There are some examples out there, please search. – Ole V.V. Apr 09 '20 at 13:03