Date() 对象不一致。月、日、年都错了

发布于 2024-10-21 21:46:58 字数 260 浏览 1 评论 0 原文

现在是 2011 年 3 月 15 日,当我调用新的日期对象时:

Date now = new Date();

我返回的

  • 月份为 2 (getMonth()),
  • 日期为 2 ( getDay())
  • 和年份 (getYear()) 为 111。

这种约定有什么原因吗?

Right now is 3/15/11 and when I'm calling a new date object:

Date now = new Date();

I'm getting in return

  • the month as 2 (getMonth()),
  • the day as 2 (getDay())
  • and the year (getYear()) as 111.

Is there a reason for this convention?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

窗影残 2024-10-28 21:46:58

直接来自类的文档

  • 年份 y 由整数 y - 1900 表示。
  • 月份用0到11之间的整数表示; 0 是一月,1 是二月,依此类推;因此 11 是 12 月。
  • 日期(一月中的某一天)按照通常的方式由 1 到 31 之间的整数表示。

至于 getDay ()

返回该日期代表的星期几。返回值(0 = 星期日、1 = 星期一、2 = 星期二、3 = 星期三、4 = 星期四、5 = 星期五、6 = 星期六)表示包含此表示的时间点或以此时间点开始的星期几日期对象,按本地时区解释。

2011 年 3 月 15 日实际上是星期二。

Straight from the class's documentation:

  • A year y is represented by the integer y - 1900.
  • A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
  • A date (day of month) is represented by an integer from 1 to 31 in the usual manner.

And as for getDay():

Returns the day of the week represented by this date. The returned value (0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday) represents the day of the week that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

March 15th 2011 is in fact a Tuesday.

圈圈圆圆圈圈 2024-10-28 21:46:58

这个约定有什么理由吗?

原因是它是 Date 的 javadoc 所指定的;请参阅@matt b 的回答。

Date API 是在 JDK 1.0 时代创建的,众所周知,它在许多领域都存在问题。这就是为什么大多数 Date 方法被标记为“已弃用”的原因。 (顺便说一句,这意味着建议您不要在新代码中使用它们!)

Calendar API 是对 Date 的重大改进,但是迄今为止,在 Java 中处理日期/时间值的最佳 API 是第 3 方 Joda time API。


如果您想要 Joda 时间使用的示例,请查看上面的链接。 GregorianCalendar< 中有一个日历使用示例/code>javadocs。有关日历使用的更多示例,请参见此页面

Is there a reason for this convention?

The reason is that it is what the javadoc for Date specifies; see @matt b's answer.

The Date APIs were created in the days of JDK 1.0, and are well known to be problematic in a number of areas. That is why most of the Date methods are marked as Deprecated. (By the way, that means that it is recommended that you don't use them in new code!!)

The Calendar APIs are a significant improvement on Date, but the best by far APIs for handling date / time values in Java are the 3rd-party Joda time APIs.


If you want examples of Joda time usage, look at the link above. There's an example of Calendar usage in the GregorianCalendar javadocs. More examples of Calendar usage may be found on this page.

场罚期间 2024-10-28 21:46:58

tl;dr

LocalDate                              // Modern class to represent a date-only value, without time-of-day, without time zone or offset-from-UTC.
.now( ZoneId.of( "Africa/Tunis" ) )    // Capture the current date as seen in the wall-clock time used by the people of a specific region (a time zone).
.getYear()                             // Get year number, such as 2019 presently.

…and:

.getMonthValue()                       // Get month number, 1-12 for January-December.

…and:

.getDayOfMonth()                       // Get day-of-month number, 1-31.

详细信息

显然,您正在使用两个可怕的日期时间类中的任何一个:java.util.Datejava.sql.Date。随着 JSR 310 的采用,它们都已经过时了,定义了它们的替代品,即现代的 java.time 类。

LocalDate

LocalDate 类表示仅日期值,没有时间且没有 时区相对 UTC 的偏移量

时区对于确定日期至关重要。对于任何特定时刻,全球各地的日期都会因地区而异。例如,在法国巴黎午夜过后几分钟,又是新的一天“昨天”在魁北克蒙特利尔

如果未指定时区,JVM 会隐式应用其当前的默认时区。该默认值可能在运行时随时更改(!),因此您的结果可能会有所不同。最好明确指定您想要/预期的时区作为参数。如果重要,请与您的用户确认该区域。

大陆/地区格式指定正确的时区名称 ,例如美国/蒙特利尔非洲/卡萨布兰卡太平洋/奥克兰。切勿使用 2-4 个字母的缩写,例如 ESTIST,因为它们不是真正的时区,不是标准化的,甚至不是唯一的( !)。

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

如果您想使用 JVM 当前的默认时区,请询问它并作为参数传递。如果省略,代码读起来会变得不明确,因为我们不确定您是否打算使用默认值,或者您是否像许多程序员一样没有意识到这个问题。

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

或者指定一个日期。您可以用数字设置月份,1 月至 12 月的合理编号为 1-12。

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

或者,更好的是,使用 Month 预定义的枚举对象,一个代表一年中的每个月。提示:在整个代码库中使用这些 Month 对象,而不仅仅是整数,可以使您的代码更加自记录,确保有效值,并提供 类型安全年份 & YearMonth

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

访问日期的部分

java.time 类使用合理的编号,1-12 表示月份,1-7 表示星期几,年份编号(例如 2019 年)是 2019 年,等等。

int year = ld.getYear() ;                 // The year, such as 2019 presently.
int monthNumber = ld.getMonthValue() ;    // Number of the month 1-12 for January-December.
Month month = ld.getMonth() ;             // Get the `Month` enum object, one of a dozen predefined objects (one for each month of the year). 
int dayOfMonth = ld.getDayOfMonth() ;     // Get the day of the month, 1-31. 

关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, 日历, & ; SimpleDateFormat

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310

Joda-Time 项目,现已在 维护模式,建议迁移到 java.time 类。

您可以直接与数据库交换java.time对象。使用符合 JDBC 驱动程序 /jeps/170" rel="nofollow noreferrer">JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 类。

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time 。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 间隔YearWeek<代码>YearQuarter,以及更多

tl;dr

LocalDate                              // Modern class to represent a date-only value, without time-of-day, without time zone or offset-from-UTC.
.now( ZoneId.of( "Africa/Tunis" ) )    // Capture the current date as seen in the wall-clock time used by the people of a specific region (a time zone).
.getYear()                             // Get year number, such as 2019 presently.

…and:

.getMonthValue()                       // Get month number, 1-12 for January-December.

…and:

.getDayOfMonth()                       // Get day-of-month number, 1-31.

Details

Apparently you are using either of two terrible date-time classes, java.util.Date or java.sql.Date. Both are outmoded as of the adoption of JSR 310, defining their replacement, the modern java.time classes.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety. Ditto for Year & YearMonth.

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

Accessing parts of a date

The java.time classes use sane numbering, 1-12 for months, 1-7 for days of the week, the year number such as 2019 is the year 2019, and such.

int year = ld.getYear() ;                 // The year, such as 2019 presently.
int monthNumber = ld.getMonthValue() ;    // Number of the month 1-12 for January-December.
Month month = ld.getMonth() ;             // Get the `Month` enum object, one of a dozen predefined objects (one for each month of the year). 
int dayOfMonth = ld.getDayOfMonth() ;     // Get the day of the month, 1-31. 

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文