我是在java中使用日期、时间和时区的新手,所以不要严格判断)。我正在开发一个在当前日期将消息写入数据库的应用程序。但有一种情况,消息可能来自不同的时区,因此,这是一个不同的时间,并且它不会与我发送到数据库的时间一致。
我收到值“2021-07-28 15:30:00 Europe/Minsk” - 带时区的日期时间(也可以采用 UTC),“Asia/Kamchatka” - 日期和时间所在的时区应该转换。我想知道时区“欧洲/明斯克”的日期“2021-07-28 15:30:00 亚洲/堪察加半岛”。
问题是,在添加时区(亚洲/堪察加半岛)的时间时,会出现一种情况:2021-07-28 15:30:00 + 9 = 2021-07-29 00:30。在没有时间的情况下进行所有计算后,我需要获得一个日期。
最佳答案
I want to know the DATE "2021-07-28 15:30:00 Asia / Kamchatka" in the timezone "Europe / Minsk".
您可以使用ZonedDateTime#withZoneSameInstant
以满足这个要求。
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.
您可以使用ZonedDateTime#toLocalDate
以满足这个要求。
演示:
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());
}
}
输出:
2021-07-28T15:30+12:00[Asia/Kamchatka]
2021-07-28T06:30+03:00[Europe/Minsk]
2021-07-28
从 Trail: Date Time 了解有关现代日期时间 API 的更多信息。
注意:下面引用的是 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.
如果是这种情况,在解析日期时间字符串之前,需要删除 /
分隔符前后的空格字符。您可以按如下方式进行操作:
String strDateTime = "2021-07-28 15:30:00 Asia / Kamchatka";
strDateTime = strDateTime.replaceAll("\\s+/\\s+", "/");
其余代码将按原样运行。
关于java - 更改日期时如何将日期和时间从一个时区转移到另一时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68560757/