How to create Java 8 Clock for a specific date

In terms of date dependent unit tests, I figure out the correct way to generate Java 8 Clock for a specific date. Following the approach suggested in the Java 8 Clock class testing unit , I am trying to use it Clock.fixed

. However, I don't understand how to do this.

Is this the correct and best way to create a Java 8 Clock for a specific date?

version 2 (as suggested by @Meno , @LakiGeri and @ Basil Bourke )

private static Clock utcClockOf(int year, int month, int day) {
    ZoneOffset offset = ZoneOffset.UTC;
    Instant inst = LocalDate
            .of(year, month, day)
            .atStartOfDay(offset)
            .toInstant();
    return Clock.fixed(inst, offset.normalized());
}

      

version 1

static Clock clockOf(int year, int month, int day) {
    LocalDate now = LocalDate.of(year, month, day);
    long days = now.toEpochDay();
    long secs = days*24*60*60;
    Instant inst = Instant.ofEpochSecond(secs);
    return Clock.fixed(inst, ZoneId.systemDefault());
}

      

+3


source to share





All Articles