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

标签 java datetime dst gmt

在 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 date2 should 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/

相关文章:

java - 如何使用 Selenium 和 Java 在自动化测试中单击按钮

Java 脚本 XSLT 错误 : For extension function, 找不到方法 java.lang.String。 ([ExpressionContext,] #STRING)

java - 删除包含特定字符的数组列表中的所有字符串

mysql - 如何将 MySQL DateTime(不是 TIMESTAMP)的默认值设置为 NOW() 或 Current_DateTIme?

java - 以秒为单位获取两个 Joda 日期之间的差异

java - System.currentTimeMillis() 返回的值是否受夏令时和闰秒调整的影响?

mysql - 夏令时问题

java - 使用 hibernate 在 maven 项目中找不到 hibernate.properties

php - 在 PHP 中解析日期字符串

java - 从 java.util.TimeZone 转换为 org.joda.DateTimeZone