我们是否已经在Java 8中设置了CurrentMillisFixed?

时间:2018-07-17 12:15:22

标签: java-8 zoneddatetime

在Joda中,我们有setCurrentMillisFixed方法,可用于设置当前系统时间:

DateTimeUtils.setCurrentMillisSystem();

在Java 8中,我正在尝试:

ZonedDateTime.now(Clock.systemDefaultZone());

但是很多测试用例都失败了,我想这与日期的设置有关。

类似地,为了快速转发时间,在Joda中

DateTimeUtils.setCurrentMillisFixed(theFuture);

在Java 8中,我尝试过:

ZonedDateTime.now().toInstant().plusMillis());

我做错什么了吗?

2 个答案:

答案 0 :(得分:2)

Clock有多种变体,您可以使用Clock.fixed(...)始终返回指定的时刻。

答案 1 :(得分:1)

通过Clock实现

Answer by Jonathan是正确的。 Clock类提供了几种说谎的替代实现,以方便测试。这是有关如何使用它们的更多说明。

java.time 中的每个now方法都带有一个可选的Clock参数。

代表时刻的类:

代表时刻的类:

如果省略,您将获得系统默认的Clock实现,即真正的时钟。

Clock类提供了一些方便的替代实现,可以通过调用静态类方法获得这些实现。有关说明的列表,请参见my Answer on a similar Question

如果出于测试目的要用错误时钟覆盖该真实时钟,请通过其他一些Clock实现。

例如,我们制作了一个Clock,它错误地报告了固定的单个时刻,即一个没有“滴答”的时钟。我们将那一刻设为从现在开始两个小时。

Clock twoHoursFuture = 
    Clock.fixed( 
        Instant.now().plus( Duration.ofHours( 2 ) ) ,  // Capture the current moment, then add a `Duration` span-of-time of two hours. Result is a moment in the future.
        ZoneId.systemDefault()                         // Or specify another time zone if that is an aim of your testing.
    )
;

给出如下代码:

public void someMethod( Clock clock ) {
    …
    ZonedDateTime zdt = ZonedDateTime.now( clock ) ;
    …
}

…您的测试工具通过了错误的时钟:

// Test harness passes `twoHoursFuture`.
someObject.someMethod( twoHoursFuture ) ;

…当您的生产代码通过调用Clock.systemDefaultZone()获得的真实时钟时:

// Production-code passes the result of calling `Clock.systemDefaultZone()`.
someObject.someMethod( Clock.systemDefaultZone() ) ;

关于 java.time

java.time框架已内置在Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendarSimpleDateFormat

目前位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解更多信息,请参见Oracle Tutorial。并在Stack Overflow中搜索许多示例和说明。规格为JSR 310

您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*类。

在哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展了java.time。该项目为将来可能在java.time中添加内容提供了一个试验场。您可能会在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore