gpt4 book ai didi

java - 返回给定日期的 BST/GMT

转载 作者:行者123 更新时间:2023-12-02 05:16:48 25 4
gpt4 key购买 nike

在 Java 中,确定特定区域设置的任何给定 Date 对象的夏令时的可接受方法是什么。

例如,如果您有两个日期对象

Date date = new Date("01/01/2014");
Date date2 = new Date("01/07/2014");

区域设置为“Europe/London”,“date”应返回 GMT,date2 应返回“BST”

    String timeZone = new String("Europe/London");
TimeZone tz = TimeZone.getTimeZone(timeZone);
System.out.println(tz.getDisplayName(tz.inDaylightTime(date),
TimeZone.SHORT));

TimeZone tz2 = TimeZone.getTimeZone(timeZone);
System.out.println(tz2.getDisplayName(tz2.inDaylightTime(date2),
TimeZone.SHORT));

这两个示例都打印 GMT,第二个不应该打印 BST 吗?

最佳答案

java.time

旧版日期时间 API(java.util 日期时间类型及其格式化类型 SimpleDateFormat)已过时且容易出错。建议完全停止使用它并切换到java.timemodern date-time API *

And the locale was "Europe/London", 'date' should return GMT and date2should return "BST"

请注意,Europe/London 是一个时区 ( ZoneId ),而不是 Locale 。 Java SE 8 日期时间 API (java.time) 为我们提供 ZonedDateTime它根据 DST 自动调整时区偏移过渡。

演示:

import java.time.LocalDate;
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 dtfInput = DateTimeFormatter.ofPattern("d/M/u", Locale.ENGLISH);
LocalDate date = LocalDate.parse("01/01/2014", dtfInput);
LocalDate date2 = LocalDate.parse("01/07/2014", dtfInput);

ZoneId zoneId = ZoneId.of("Europe/London");

ZonedDateTime zdt = date.atStartOfDay(zoneId);
ZonedDateTime zdt2 = date2.atStartOfDay(zoneId);

DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("dd/MM/uuuu'['z']'", Locale.ENGLISH);
System.out.println(zdt.format(dtfOutput));
System.out.println(zdt2.format(dtfOutput));
}
}

输出:

01/01/2014[GMT]
01/07/2014[BST]

了解有关 java.time 的更多信息,modern date-time API * 来自 Trail: Date Time

<小时/>

* 无论出于何种原因,如果您必须坚持使用 Java 6 或 Java 7,则可以使用 ThreeTen-Backport它将大部分 java.time 功能向后移植到 Java 6 和 7。如果您正在从事 Android 项目,并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

关于java - 返回给定日期的 BST/GMT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26867952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com