LocalDate.of( 1985 , 1 , 1 )
…要么…
LocalDate.of( 1985 , Month.JANUARY , 1 )
细节
的java.util.Date,java.util.Calendar和java.text.SimpleDateFormat班级被送往太快时的Java首次推出和发展。这些类的设计或实施不正确。已尝试进行改进,因此发现了不推荐使用的地方。不幸的是,改进的尝试在很大程度上失败了。您应该完全避免这些类。它们在Java 8中被新类取代。
代码中的问题
java.util.Date同时具有日期和时间部分。您忽略了代码中的时间部分。因此,Date类将采用JVM的默认时区所定义的一天的开始时间,并将该时间应用于Date对象。因此,代码的结果将根据它运行的计算机或设置的时区而有所不同。可能不是您想要的。
如果只想要日期,而没有时间部分,例如出生日期,则可能不想使用Date对象。您可能只想以ISO 8601格式存储日期的字符串YYYY-MM-DD。或使用LocalDateJoda-Time中的对象(请参见下文)。
乔达时代
用Java学习的第一件事:避免与Java捆绑在一起的臭名昭著的java.util.Date和java.util.Calendar类。
正如user3277382的答案正确指出的那样,请在Java 8中使用Joda-Time或新的java.time。*包。
Joda-Time 2.3中的示例代码
DateTimeZone timeZoneNorway = DateTimeZone.forID( "Europe/Oslo" );
DateTime birthDateTime_InNorway = new DateTime( 1985, 1, 1, 3, 2, 1, timeZoneNorway );
DateTimeZone timeZoneNewYork = DateTimeZone.forID( "America/New_York" );
DateTime birthDateTime_InNewYork = birthDateTime_InNorway.toDateTime( timeZoneNewYork );
DateTime birthDateTime_UtcGmt = birthDateTime_InNorway.toDateTime( DateTimeZone.UTC );
LocalDate birthDate = new LocalDate( 1985, 1, 1 );
转储到控制台...
System.out.println( "birthDateTime_InNorway: " + birthDateTime_InNorway );
System.out.println( "birthDateTime_InNewYork: " + birthDateTime_InNewYork );
System.out.println( "birthDateTime_UtcGmt: " + birthDateTime_UtcGmt );
System.out.println( "birthDate: " + birthDate );
运行时...
birthDateTime_InNorway: 1985-01-01T03:02:01.000+01:00
birthDateTime_InNewYork: 1984-12-31T21:02:01.000-05:00
birthDateTime_UtcGmt: 1985-01-01T02:02:01.000Z
birthDate: 1985-01-01
java.time
在这种情况下,java.time的代码与Joda-Time几乎相同。
我们得到一个时区(ZoneId),并构造一个分配给该时区(ZonedDateTime)的日期时间对象。然后,使用不可变对象模式,我们根据旧对象的同一瞬间(自epoch以来的纳秒数)创建了新的日期时间,但分配了其他时区。最后,我们得到一个LocalDate没有时间和时区的,尽管在确定该日期时会注意到时区适用(例如,奥斯陆比纽约早到了新的一天)。
ZoneId zoneId_Norway = ZoneId.of( "Europe/Oslo" );
ZonedDateTime zdt_Norway = ZonedDateTime.of( 1985 , 1 , 1 , 3 , 2 , 1 , 0 , zoneId_Norway );
ZoneId zoneId_NewYork = ZonedId.of( "America/New_York" );
ZonedDateTime zdt_NewYork = zdt_Norway.withZoneSameInstant( zoneId_NewYork );
ZonedDateTime zdt_Utc = zdt_Norway.withZoneSameInstant( ZoneOffset.UTC ); // Or, next line is similar.
Instant instant = zdt_Norway.toInstant(); // Instant is always in UTC.
LocalDate localDate_Norway = zdt_Norway.toLocalDate();
关于java.time
该java.time框架是建立在Java 8和更高版本。这些类取代麻烦的老传统日期时间类,如java.util.Date,Calendar,和SimpleDateFormat。
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
要了解更多信息,请参见Oracle教程。并在Stack Overflow中搜索许多示例和说明。规格为JSR 310。
您可以直接与数据库交换java.time对象。使用与JDBC 4.2或更高版本兼容的JDBC驱动程序。不需要字符串,不需要类。java.sql.*
在哪里获取java.time类?
Java SE 8, Java SE 9, Java SE 10和更高版本
内置的
标准Java API的一部分,具有捆绑的实现。
Java 9添加了一些次要功能和修复。
Java SE 6和 Java SE 7
java.time的许多功能在ThreeTen- Backport中都被反向移植到Java 6和7 。
安卓系统
更高版本的Android捆绑了java.time类的实现。
对于早期的Android(<26),ThreeTenABP项目改编了ThreeTen-Backport(如上所述)。请参阅如何使用ThreeTenABP…。
该ThreeTen-额外项目与其他类扩展java.time。该项目为将来可能在java.time中添加内容提供了一个试验场。你可能在这里找到一些有用的类,比如Interval,YearWeek,YearQuarter,和更多。