DateUtil.java

  1. package no.nav.data.common.utils;

  2. import java.lang.management.ManagementFactory;
  3. import java.time.Duration;
  4. import java.time.LocalDate;
  5. import java.time.LocalDateTime;
  6. import java.time.format.DateTimeFormatter;
  7. import java.time.format.FormatStyle;
  8. import java.util.Locale;

  9. public final class DateUtil {

  10.     public static final String DEFAULT_START = "0001-01-01";
  11.     public static final String DEFAULT_END = "9999-12-31";
  12.     public static final Locale LOCALE_NB = Locale.forLanguageTag("nb");
  13.     public static final DateTimeFormatter NORWEGIAN_FORMAT = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(LOCALE_NB);

  14.     private DateUtil() {
  15.     }

  16.     public static String formatDateTime(LocalDateTime dateTime) {
  17.         return dateTime == null ? null : dateTime.format(DateTimeFormatter.ISO_DATE_TIME);
  18.     }

  19.     public static String formatDateTimeHumanReadable(LocalDateTime dateTime) {
  20.         return dateTime == null ? null : dateTime.format(NORWEGIAN_FORMAT);
  21.     }

  22.     public static String formatDate(LocalDate date) {
  23.         return date == null ? null : date.format(DateTimeFormatter.ISO_DATE);
  24.     }

  25.     public static boolean isNow(LocalDate start, LocalDate end) {
  26.         return (start == null || start.minusDays(1).isBefore(LocalDate.now())) &&
  27.                 (end == null || end.plusDays(1).isAfter(LocalDate.now()));
  28.     }

  29.     public static LocalDate parse(String date) {
  30.         return date == null ? null : LocalDate.parse(date);
  31.     }

  32.     public static LocalDate parseStart(String start) {
  33.         return start == null ? parse(DEFAULT_START) : parse(start);
  34.     }

  35.     public static LocalDate parseEnd(String end) {
  36.         return end == null ? parse(DEFAULT_END) : parse(end);
  37.     }

  38.     public static Duration uptime() {
  39.         return Duration.ofMillis(ManagementFactory.getRuntimeMXBean().getUptime());
  40.     }
  41. }