gpt4 book ai didi

java - SimpleDateFormat 在字符串中也存在时忽略时区

转载 作者:行者123 更新时间:2023-11-30 05:36:22 28 4
gpt4 key购买 nike

Java 的 SimpleDateFormat允许您指定 TimeZone将字符串解析为 Date 时使用.

当字符串不包含时区时,这将按您的预期工作,但当存在时区时,它似乎什么也不做。

文档似乎也没有真正解释如何使用 TimeZone。

示例代码:

public class DateFormatTest {
public static void main(final String[] args) throws ParseException {
testBoth("HH:mm", "13:40");
testBoth("HH:mm z", "13:40 UTC");
}

private static void testBoth(final String dateFormatString, final String dateString) throws ParseException {
// First, work with the "raw" date format
DateFormat dateFormat = new SimpleDateFormat(dateFormatString);
parse(dateFormat, dateString);

// Now, set the timezone to something else and try again
dateFormat = new SimpleDateFormat(dateFormatString);
dateFormat.setTimeZone(TimeZone.getTimeZone("PST"));
parse(dateFormat, dateString);
}

private static void parse(final DateFormat dateFormat, final String dateString) throws ParseException {
System.out.println(MessageFormat.format("Parsed \"{0}\" with timezone {1} to {2}", dateString,
dateFormat.getTimeZone().getDisplayName(), dateFormat.parse(dateString)));
}
}

示例输出:

Parsed "13:40" with timezone Greenwich Mean Time to 01/01/70 13:40
Parsed "13:40" with timezone Pacific Standard Time to 01/01/70 22:40
Parsed "13:40 UTC" with timezone Greenwich Mean Time to 01/01/70 14:40
Parsed "13:40 UTC" with timezone Pacific Standard Time to 01/01/70 14:40

请注意,对于第一个示例,日期会发生变化 - 但对于第二个示例,日期不会发生变化。

最佳答案

类型错误

您使用了错误的数据类型,试图将日期时间值放入包含日期时间和日期以及与 UTC 的偏移量(零)的类型中。 Square peg, round hole .

此外,java.util.Date 类的设计和实现都非常出色。几年前,随着 JSR 310 的采用,它被现代 java.time 类取代。

当天时间:本地时间

"13:40"

简单地解析为 LocalTime 对象。

LocalTime lt = LocalTime.parse( "13:40" ) ;

如果您想结合日期和时区来确定时刻,请应用 LocalDateZoneId 来生成 ZonedDateTime对象。

ZoneId z = ZoneId.of( "America/Los_Angeles" ) ;
LocalDate today = LocalDate.now( z ) ;
ZonedDateTime zdt = ZonedDateTime.of( today , lt , z ) ;

要查看 UTC 中的同一时刻,请提取即时

Instant instant = zdt.toInstant() ; 

与 UTC 的偏移量的时间:OffsetTime

"13:40 UTC"

一天中的某个时间 time zoneoffset-from-UTC实际上没有意义。如果没有日期,就无法以有意义的方式来思考与特定时区相关的时间。没有人能够向我解释一个例子,说明这在逻辑上如何有意义。我听到的每一次尝试实际上都涉及一个隐含的日期。

尽管如此,SQL 标准委员会还是明智地决定定义TIME WITH TIME ZONE 数据类型。因此,为了支持这一点,java.time 类包含一个匹配的类 OffsetTime

不幸的是,我找不到可以解析输入末尾的 SPACE 和 UTC 的格式模式。因此,作为解决方法,我建议将这些字符替换为单个 Z 字符。因此,“13:40 UTC” 变为 “13:40Z”Z 表示 UTC,发音为“Zulu”。默认情况下会处理此格式,因此无需指定格式模式。

String input = "13:40 UTC".replace( " UTC" , "Z" ) ;  // "13:40 UTC" becomes "13:40Z".
OffsetTime ot = OffsetTime.parse( input ) ;

Table of date-time types in Java (both modern and legacy) and in standard SQL.

关于java - SimpleDateFormat 在字符串中也存在时忽略时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56527319/

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