Java DateFormat parse() 不尊重时区

2023-06-28Java开发问题
19

本文介绍了Java DateFormat parse() 不尊重时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"));
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
df.setTimeZone(TimeZone.getTimeZone("America/New_York"));

try {
    System.out.println(df.format(cal.getTime()));
    System.out.println(df.parse(df.format(cal.getTime())));
} catch (ParseException e) {
    e.printStackTrace();
}

结果如下:

2011-09-24 14:10:51 -0400

2011-09-24 14:10:51 -0400

2011 年 9 月 24 日星期六 20:10:51 CEST

Sat Sep 24 20:10:51 CEST 2011

为什么当我解析从 format() 获得的日期时,它不遵守时区?

Why when I parse a date I get from format() it doesn't respect the timezone?

推荐答案

你正在打印调用 Date.toString()总是使用默认时区.基本上,您不应该将 Date.toString() 用于除调试以外的任何事情.

You're printing the result of calling Date.toString(), which always uses the default time zone. Basically, you shouldn't use Date.toString() for anything other than debugging.

不要忘记 Date 没有时区 - 它代表时间的瞬间,以 Unix 纪元以来的毫秒数(1 月的午夜1970 UTC).

Don't forget that a Date doesn't have a time zone - it represents an instant in time, measured as milliseconds since the Unix epoch (midnight on January 1st 1970 UTC).

如果您再次使用格式化程序格式化日期,应该会得出与以前相同的答案.

If you format the date using your formatter again, that should come up with the same answer as before.

顺便说一句,我建议使用 Joda Time 而不是 Date/Calendar 如果你在 Java 中做大量的日期/时间工作;这是一个非常更好的 API.

As an aside, I would recommend the use of Joda Time instead of Date/Calendar if you're doing any significant amount of date/time work in Java; it's a much nicer API.

这篇关于Java DateFormat parse() 不尊重时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13