How to transfer date and time from one time zone to another when changing the date?

Viewed 116

I'm new to working with dates, times and timezones in java, so don't judge strictly). I am developing an application that writes messages to the database at the current date. But there is a situation when a message may come to me from a different timezone and, accordingly, this is a different time and it will not coincide with my time, which I send to the database.

I receive the value "2021-07-28 15:30:00 Europe / Minsk" - date-time with timezone (It can also come in UTC), "Asia / Kamchatka" - timezone into which the date and time should be converted. I want to know the DATE "2021-07-28 15:30:00 Asia / Kamchatka" in the timezone "Europe/Minsk".

The catch is that there is a situation when, when adding time in the time zone (Asia/Kamchatka) 2021-07-28 15: 30: 00 + 9 = 2021-07-29 00:30. I need to get a DATE after all calculations without time.

1 Answers

I want to know the DATE "2021-07-28 15:30:00 Asia / Kamchatka" in the timezone "Europe / Minsk".

You can use ZonedDateTime#withZoneSameInstant to meet this requirement.

The catch is that there is a situation when, when adding time in the time zone (Asia / Kamchatka) 2021-07-28 15: 30: 00 + 9 = 2021-07-29 00:30. I need to get DATE after all calculations without time.

You can use ZonedDateTime#toLocalDate to meet this requirement.

Demo:

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d H:m:s z", Locale.ENGLISH);
        String strDateTime = "2021-07-28 15:30:00 Asia/Kamchatka";
        ZonedDateTime zdtInput = ZonedDateTime.parse(strDateTime, dtf);
        ZonedDateTime zdtOuput = zdtInput.withZoneSameInstant(ZoneId.of("Europe/Minsk"));
        System.out.println(zdtInput);
        System.out.println(zdtOuput);
        System.out.println(zdtOuput.toLocalDate());
    }
}

Output:

2021-07-28T15:30+12:00[Asia/Kamchatka]
2021-07-28T06:30+03:00[Europe/Minsk]
2021-07-28

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

Note: Quoted below is a valuable comment by Basil Bourque:

The example data in Question shows time zone names incorrectly spelled with a SPACE character on each side of the slash. I suggest you add a bit of code using String#replace to substitute the single character "/" for triple character " / " before parsing.

If it is the case, before parsing the date-time string, you need to remove the whitespace characters before and after the / separator. You can do so as follows:

String strDateTime = "2021-07-28 15:30:00 Asia / Kamchatka";
strDateTime = strDateTime.replaceAll("\\s+/\\s+", "/");

Rest of the code will work as it is.

Related