Java 日期 (0) 不是 1/1/1970

标签 java

我原以为它会打印 1970-01-01-00:00:00,但它打印的是 1970-12-31-19:00:00

我对 Date 的计算方式有什么误解?这是一年的假期。我在带有 JDK 1.6 的 Windows 7 上运行这个

System.out.println(new SimpleDateFormat("YYYY-MM-dd-HH:mm:ss").format(new Date(0)));

最佳答案

它不仅仅是时区 - 它是使用时区的混合,使用YYYY表示而不是年份(从 Java 7 开始)。将其更改为 yyyy,您将看到 1969。

docs on week years状态:

Values calculated for the WEEK_OF_YEAR field range from 1 to 53. The first week of a calendar year is the earliest seven day period starting on getFirstDayOfWeek() that contains at least getMinimalDaysInFirstWeek() days from that year. It thus depends on the values of getMinimalDaysInFirstWeek(), getFirstDayOfWeek(), and the day of the week of January 1. Weeks between week 1 of one year and week 1 of the following year (exclusive) are numbered sequentially from 2 to 52 or 53 (except for year(s) involved in the Julian-Gregorian transition).

The getFirstDayOfWeek() and getMinimalDaysInFirstWeek() values are initialized using locale-dependent resources when constructing a GregorianCalendar. The week determination is compatible with the ISO 8601 standard when getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4, which values are used in locales where the standard is preferred. These values can explicitly be set by calling setFirstDayOfWeek() and setMinimalDaysInFirstWeek().

A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the first and last weeks (inclusive) have the same week year value. Therefore, the first and last days of a week year may have different calendar year values.

所以问题是1969年“平年”的最后一天实际上是1970年的“周年”。

您应该绝对使用yyyy 以避免混淆 - 周年相对很少有用,而且很容易造成混淆,正如我们所见:)

编辑:如评论中所述,您确定您没有使用 Java 7 吗? docs for SimpleDateFormat in 1.6别提了...也许您在 1.6 中编译但在 7 中运行

关于Java 日期 (0) 不是 1/1/1970,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7895171/

相关文章:

java - 如何在 thymeleaf 中使用列表来使用输入类型?

java - H2 数据库模式创建检查

java - 设置自定义字段名称和代码

java - 根据属性从 Arraylist 获取元素 - Java

java - Java 7 中是否有等效的 getRequestedServerNames()?

java - 如何使用 java 13 设置 spring-boot 应用程序

java - 检查 o(n) 中数组左侧的总和是否等于数组右侧的总和

java - 如何在隐藏一个 JFrame 的同时将一个 JFrame 移动到另一个 JFrame

java - 大比较任务的估计

java - 如何在选项卡 Activity 中调用微调器?