Search code examples
java-8java-timetimezone-offset

Java LocalDateTime with offset


The task is to convert current date time to that format:

  2023-06-28T12:00:01.545+0300

For this purporse I use the following approach:

 String currentDateTime =
    DateTimeFormatter.ISO_LOCAL_DATE_TIME
            .format(LocalDateTime.now().atOffset(ZoneOffset.UTC));

But it returns:

 2023-06-28T12:00:01.545

What am I missing?


Solution

  • ISO_LOCAL_DATE_TIME, as its name suggests, only produces local date times - date times without a zone/offset.

    You should use ISO_DATE_TIME instead.

    Also, getting the current LocalDateTime and then adding an offset to it doesn't make much sense to me, not to mention that you are adding an offset of 0 (UTC), instead of the +03:00 that you expect in your output.

    To get a OffsetDateTime at +03:00 that represents the current instant, use the OffsetDateTime.now overload that takes a ZoneId.

    String currentDateTime =
            DateTimeFormatter.ISO_DATE_TIME
                    .format(OffsetDateTime.now(ZoneOffset.ofHours(3)));
            System.out.println(currentDateTime);
    

    Example output:

    2023-06-28T15:12:05.752631+03:00
    

    If you want the offset to be in the format of +0300 instead, use a DateTimeFormatterBuilder, which allows you to specify a custom offset format.

    String currentDateTime =
            new DateTimeFormatterBuilder()
                    // first append the date time without an offset
                    .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                    // then append the offset - here I'm assuming you want "0000" for a 0 offset
                    .appendOffset("+HHMM", "0000")
                    .toFormatter()
                    .format(OffsetDateTime.now(ZoneOffset.ofHours(3)));
            System.out.println(currentDateTime);