Search code examples
java-8timezonejodatimesimpledateformatzoneddatetime

How to get TimeZone offset value in java


I have a date coming from a device and I want to do the following in Java:

  1. I want to parse this date "2021-05-27T18:47:07+0530" to yyyy-mm-dd HH:MM:SS
  2. Get the Date's offset value so that I can get the timezone offset as +05:30 or whatever timezone it comes from.

For the first one I have done this and looks like it works, but any better smaller approach will be handy as well:


        String date = "2021-05-27T18:47:07+0530";
        String inputPattern = "yyyy-MM-dd'T'HH:mm:ss+SSSS";
        String outputPattern = "yyyy-MM-dd HH:mm:ss";
        LocalDateTime inputDate = null;
        String outputDate = null;
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);
        inputDate = LocalDateTime.parse(date, inputFormatter);
        outputDate = outputFormatter.format(inputDate);
        System.out.println("inputDate: " + inputDate);
        System.out.println("outputDate: " + outputDate);

The Ouput is:

inputDate: 2021-05-27T18:47:07.053
outputDate: 2021-05-27 18:47:07

I don't know how to get the offset value of timezone in this case.

There are many recommendations including using SimpleDateFormat and ZonedDateTime etc but should be the best answer for this considering the offset value can be dynamic i.e it can be +05:30,+09:00 etc.

Please help in this case.


Solution

  • Try it like this.

    String dateTime = "2021-05-27T18:47:07+0530";
    String inputPattern = "yyyy-MM-dd'T'HH:mm:ssZ";
    String outputPattern = "yyyy-MM-dd HH:mm:ss";
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ", 
        Locale.ENGLISH);
    ZonedDateTime zdt = ZonedDateTime.parse(dateTime, dtf);
    ZoneOffset tz = zdt.getOffset();
    System.out.println(tz);
    System.out.println(zdt.format(DateTimeFormatter.ofPattern(outputPattern,
            Locale.ENGLISH)));
    

    Prints

    +05:30
    2021-05-27 18:47:07
    

    The zoned date time could also be reprinted using the same format by which it was originally parsed.