tl;博士
使用 java.time 类而不是麻烦的遗留类。
要获得一天的第一时间,请致电LocalDate.atStartOfDay( ZoneId )。
LocalDate.now( // Represent the date alone, without time-of-day and without time zone.
ZoneId.of( "Africa/Tunis" ) // Specify the time zone in which to determine the current date.
)
.withDayOfYear( 1 ) // Or `.withDayOfMonth(1)` or `.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY) )`.
.atStartOfDay( // Determine the first moment of the day on that particular date in that particular zone.
ZoneId.of( "Africa/Tunis" )
) // Returns a `ZonedDateTime` object.
.toInstant() // Same moment, as seen in UTC.
.toEpochMilli() // Extract a count of milliseconds since the epoch reference of 1970-01-01T00:00:00Z.
java.time
您正在使用麻烦的旧日期时间类,这些类现在已被 java.time 类取代。
获取当前日期和时间需要时区。对于任何给定的时刻,日期和时间在全球因地区而异。
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
提取该日期与时间的仅日期部分。
LocalDate ld = zdt.toLocalDate() ;
从那个日期开始,让 java.time 确定一天中的第一个时刻。永远不要假设一天从 00:00:00 开始。夏令时 (DST) 等异常情况意味着一天可能从另一个时间开始,例如 01:00:00。
java.time 类使用immutable objects。不是更改对象的属性(“变异”),而是根据原始值创建一个新的对象。
ZonedDateTime zdtResult = null ;
对于您的 switch 语句,请使用现有的 ChronoUnit 枚举。由于一个奇怪的技术问题,switch 语句不能使用限定的枚举名称。所以我们必须使用YEARS 而不是ChronoUnit.YEARS,例如,作为开关变量。使用静态导入来访问枚举。
import static java.time.temporal.ChronoUnit ;
…
switch ( unit ) {
case YEARS :
zdtResult = ld.withDayOfYear( 1 )
.atStartOfDay( z ) ;
break;
case MONTHS :
zdtResult = ld.withDayOfMonth( 1 )
.atStartOfDay( z ) ;
break;
case WEEKS :
zdtResult = ld.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY) )
.atStartOfDay( z ) ;
break;
default: …
}
从生成的ZonedDateTime 中提取Instant 对象以查看UTC 中的同一时刻。
Instant instant = zdtResult.toInstant() ;
您的问题的目标似乎是从 1970 年 UTC 第一时刻的纪元参考算起的毫秒数。我强烈建议不要仅使用 long 整数来跟踪日期时间值。使调试和跟踪变得麻烦,错误可能会被忽视。传递并存储Instant 对象。
但是,如果您坚持计数,这里是代码。请注意数据丢失,因为Instant 的分辨率为纳秒,因此此调用会忽略任何现有的微秒或纳秒。
long millisSinceEpoch = instant.toEpochMillis() ;
注意使用 java.time 如何使代码更短、更整洁、更易读。
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。