Search code examples
javadatedatetimejava-8utc

Java Instant Datetime how to get the Datetime with timezone offset only? without the region information


I am using the Java Instant to get the current date-time information, but it returns to me the UTC Datetime with Z or with [Europe/Berlin]. How do I get the only Datetime information with timezone offset?

Following is the code I have:

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;


public class Test {
    public static void main(String[] args) {
        Instant instant = Instant.now();

        System.out.println("Current Time : " + instant);

        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        System.out.println("LocalDateTime : " + localDateTime);

        ZonedDateTime zonedDateTime1 = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
        System.out.println("ZonedDateTime1: " + zonedDateTime1);
    }
}

Following is the output I have:

Current Time : 2022-04-13T08:22:35.362644Z
LocalDateTime : 2022-04-13T10:22:35.362644
ZonedDateTime1: 2022-04-13T10:22:35.362644+02:00[Europe/Berlin]

My expected output is:

expected output: 2022-04-13T10:22:35.362644+02:00

How can I get my expected output 2022-04-13T10:22:35.362644+02:00 using Instant? I am aware that I can do the substring(), but I do not want to do that. I am looking for some direct approach to achieve this. Please provide some suggestion.

Also, I do not wish to pass the region information as the application can be accessed across various regions so do not wish to hardcode the region in code.


Solution

  • I don't see why you need Instant. The following code gives your desired output:

    import java.time.ZonedDateTime;
    import java.time.format.DateTimeFormatter;
    
    public class Test {
    
        public static void main(String[] args) {
            System.out.println(ZonedDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
        }
    }
    

    When I run the above code, I get the following output:

    2022-04-13T12:25:31.1157466+03:00
    

    My local time zone is three hours ahead of UTC.