BAEL-5178:An introduction to InstantSource (#11646)

* BAEL-5178:An introduction to InstantSource

* BAEL-5178:PR fixes

Co-authored-by: Pablo Ubal <pablo.ubal@flexit.es>
This commit is contained in:
pabloubal
2022-01-13 16:12:54 +01:00
committed by GitHub
parent 7febf0b99d
commit 864c50d47b
3 changed files with 147 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
package com.baeldung.instantsource;
import java.time.Instant;
import java.time.InstantSource;
public class InstantExample {
InstantWrapper instantWrapper;
InstantSource instantSource;
public InstantExample(InstantWrapper instantWrapper, InstantSource instantSource) {
this.instantWrapper = instantWrapper;
this.instantSource = instantSource;
}
public Instant getCurrentInstantFromWrapper() {
return instantWrapper.instant();
}
public Instant getCurrentInstantFromInstantSource() {
return instantSource.instant();
}
}

View File

@@ -0,0 +1,39 @@
package com.baeldung.instantsource;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class InstantWrapper {
Clock clock;
private InstantWrapper() {
this.clock = Clock.systemDefaultZone();
}
private InstantWrapper(ZonedDateTime zonedDateTime) {
this.clock = Clock.fixed(zonedDateTime.toInstant(), zonedDateTime.getZone());
}
private InstantWrapper(LocalDateTime localDateTime) {
this.clock = Clock.fixed(localDateTime.toInstant(ZoneOffset.UTC), ZoneOffset.UTC);
}
public static InstantWrapper of() {
return new InstantWrapper();
}
public static InstantWrapper of(ZonedDateTime zonedDateTime) {
return new InstantWrapper(zonedDateTime);
}
public static InstantWrapper of(LocalDateTime localDateTime) {
return new InstantWrapper(localDateTime);
}
public Instant instant() {
return clock.instant();
}
}