Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: ZonedDateTime - parse timestring without timezone

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);
like image 791
chris01 Avatar asked Jun 28 '18 12:06

chris01


People also ask

How do I get time from ZonedDateTime?

now() now() method of a ZonedDateTime class used to obtain the current date-time from the system clock in the default time-zone. This method will return ZonedDateTime based on system clock with default time-zone to obtain the current date-time.

How do I change timezone in ZonedDateTime?

To convert a ZonedDateTime instance from one timezone to another, follow the two steps: Create ZonedDateTime in 1st timezone. You may already have it in your application. Convert the first ZonedDateTime in second timezone using withZoneSameInstant() method.

What is Z in LocalDateTime?

It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time. The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).


1 Answers

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).

like image 140
Ole V.V. Avatar answered Oct 22 '22 04:10

Ole V.V.