View Javadoc
1   package de.dlr.shepard.data.timeseries.services;
2   
3   import java.time.Duration;
4   import java.time.Instant;
5   import java.time.LocalDate;
6   import java.time.Period;
7   import java.time.ZoneId;
8   import java.time.format.DateTimeFormatter;
9   import java.time.temporal.TemporalAmount;
10  
11  /*
12   * Helper class that provides some convenience methods for handling
13   * Instants and converting them to a long in nanoseconds.
14   * All times are handled with ZoneOffset UTC and do not store any timezone information.
15   */
16  public class InstantHelper {
17  
18    private Instant instant = Instant.now();
19  
20    public static InstantHelper fromGermanDate(String dateAsString) {
21      return new InstantHelper(
22        LocalDate.parse(dateAsString, DateTimeFormatter.ofPattern("dd.MM.yyyy"))
23          .atStartOfDay(ZoneId.of("UTC"))
24          .toInstant()
25      );
26    }
27  
28    public static InstantHelper now() {
29      return new InstantHelper(Instant.now());
30    }
31  
32    public InstantHelper(Instant instant) {
33      this.instant = instant;
34    }
35  
36    /**
37     * Changes and returns the current instant object after adding a new duration/ temporal amount to it.
38     * <p>
39     * TemporalAmount is the base interface type for amounts of time.
40     * Use Period for dates and Duration for times.
41     * @param duration
42     * @return InstantHelper
43     */
44    public InstantHelper addDuration(TemporalAmount duration) {
45      instant = this.instant.plus(duration);
46      return this;
47    }
48  
49    public InstantHelper addSeconds(long seconds) {
50      return addDuration(Duration.ofSeconds(seconds));
51    }
52  
53    public InstantHelper addMinutes(long minutes) {
54      return addDuration(Duration.ofMinutes(minutes));
55    }
56  
57    public InstantHelper addHours(long hours) {
58      return addDuration(Duration.ofHours(hours));
59    }
60  
61    public InstantHelper addDays(int days) {
62      return addDuration(Period.ofDays(days));
63    }
64  
65    public InstantHelper addMonths(int months) {
66      return addDuration(Period.ofMonths(months));
67    }
68  
69    public InstantHelper addYears(int years) {
70      return addDuration(Period.ofYears(years));
71    }
72  
73    public long toNano() {
74      return this.instant.toEpochMilli() * 1_000_000;
75    }
76  }