【问题标题】:Parsing date reseting the timezone [duplicate]解析日期重置时区[重复]
【发布时间】:2020-03-02 15:17:54
【问题描述】:

我正在尝试根据机场在 Date 对象上设置时区。 当我再次将其从 String 解析为 date 时,它​​会将时区从 EST 重置为本地时区 CST。

 private Date formatDate(final Date date, final FlightStop stop) {
    DateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mm aa zzz");
    sdf.setTimeZone(TimeZone.getTimeZone(stop.getAirport().getTimeZone().getID()));

    try {
        LOG.debug("before parsing -> sdf.format(date) : " + sdf.format(date)); //03/03/20 10:45 AM EST
        LOG.debug("after parsing -> sdf.parse(sdf.format(date)) : " + sdf.parse(sdf.format(date))); //after parsing Tue Mar 03 09:45:00 CST

        return sdf.parse(sdf.format(date));

    } catch (Exception e) {
        return new Date();
    }
}

更新: 方法调用:

 public void sendMessage(final Date endingStopDate, final FlightStop endingStop) {
        Date endDate = formatDate(endingStopDate, endingStop);
        traveler.setDate(endDate);

【问题讨论】:

  • 把代码贴在你调用那个方法的地方。
  • Date & company 是一个丑陋的烂摊子,带有不直观的 API 和在单个类中混合不相关的信息。是否可以选择使用 java.time 包?它可能很复杂,但它与时间和日期一样复杂,仅此而已......
  • 我建议你不要使用DateSimpleDateFormat。这些类设计不佳且早已过时,后者尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time APIZonedDateTimeZoneId。也不要依赖三个字母的时区缩写,它们通常是模棱两可的,而且往往不是真正的时区。

标签: java date


【解决方案1】:

Date 是 UTC

您不能为java.util.Date 设置时区。该类代表 UTC 中的一个时刻。

java.time

您正在使用糟糕的日期时间类,这些类在几年前已被现代 java.time 类所取代。

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

要生成标准ISO 8601 格式的字符串,请调用toStringZonedDateTime::toString 通过在方括号中附加时区名称来明智地扩展标准。

要生成其他格式的字符串,请使用DateTimeFormatter。搜索堆栈溢出以了解更多信息。这已经被报道了数百次。

DateTimeFormatter f = DateTimeFormatter.ofPattern( … ) ;
String output = zdt.format( f );

和解析。

ZonedDateTime zdt = ZonedDateTime.parse( input , f ) ;

不要以自定义格式交换数据值。所以不要来回生成和解析您的自定义字符串。仅使用标准ISO 8601 格式以文本方式交换日期时间值。通常最好在这样做时调整到 UTC。

zdt.toInstant().toString()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-28
    • 2016-06-08
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多