DR
LocalDate // Represent a date-only, without a time-of-day and without a time zone.
.now() // Capture the current date, as seen through your JVMâs current default time zone. Better to pass a `ZoneId` as the optional argument.
.plusDays( 5 ) // Add five days, returning a new `LocalDate` object. Per the Immutable Objects pattern, a new object is produced rather than changing (âmutatingâ) the original.
.format( // Generate text representing the date value of our `LocalDate` object.
DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) // Define a formatting pattern to suit your taste. Or call the `.ofLocalizedâ¦` methods to localize automatically.
) // Returns a `String`.
Java.时间
Date
类表示以UTC表示的某一时刻、日期和时间,并且与UTC的偏移量为零。使用仅日期值时使用的类错误。
避免使用旧的日期时间类,例如
Calendar
,
日期
和
SimpleDateFormat
. 这些课程在几年前被
Java.时间
类。
不要将天数跟踪为秒或毫秒计数。天不总是24小时长,年也不总是365天长。
LocalDate
相反,使用
LocalDate
班级。
LocalDate today = LocalDate.now() ;
LocalDate later = today.plusDays( 5 ) ;
转换
最好的
避免遗留类
总而言之。但如果必须与尚未更新到的旧代码进行互操作
Java.时间
类,您可以来回转换。调用添加到旧类中的新方法。
为了
日期
您需要添加一天中的某个时间。我希望你能在一天中的第一个时刻出发。我假设您希望将日期设为UTC,而不是时区。我们必须通过
OffsetDateTime
对象添加一天中的时间和偏移量。对于偏移量,我们使用常数
ZoneOffset.UTC
. 然后我们提取更基本的
Instant
要转换为的类对象
java.util.Date
.
OffsetDateTime odt = OffsetDateTime.of( later , LocalTime.MIN , ZoneOffset.UTC ) ; // Combine the date with time-of-day and with an offset-from-UTC.
Instant instant = odt.toInstant() ; // Convert to the more basic `Instant` class, a moment in UTC, always UTC by definition.
java.util.Date d = java.util.Date.from( instant ) ; // Convert from modern class to legacy class.
往另一个方向走:
Instant instant = d.toInstant() ; // Convert from legacy class to modern class.
关于
Java.时间
这个
java.time
框架是在Java 8和之后构建的。这些阶级取代了麻烦的旧阶级。
legacy
日期时间类,如
java.util.Date
,
Calendar
和;
SimpleDateFormat
.
这个
Joda-Time
项目,现在
maintenance mode
,建议迁移到
java.time
类。
要了解更多信息,请参阅
Oracle Tutorial
. 以及搜索堆栈溢出以获得许多示例和解释。规格为
JSR 310
.
你可以换
Java.时间
直接使用数据库的对象。使用A
JDBC driver
顺从
JDBC 4.2
或稍后。不需要字符串,不需要
java.sql.*
类。
在哪里获取java.time类?
这个
ThreeTen-Extra
Project使用其他类扩展java.time。这个项目是将来可能添加到java.time的一个试验场。您可以在这里找到一些有用的类,例如
Interval
,
YearWeek
,
YearQuarter
和
more
.