From 95d93ec222d6c71623b314c266eaf205bc92d102 Mon Sep 17 00:00:00 2001 From: jomu Date: Mon, 22 Oct 2018 19:06:45 +0200 Subject: [PATCH] added Date / LocalDate conversion helper --- .../de/muehlencord/shared/util/DateUtil.java | 53 ++++++++++++------- 1 file changed, 35 insertions(+), 18 deletions(-) diff --git a/util/src/main/java/de/muehlencord/shared/util/DateUtil.java b/util/src/main/java/de/muehlencord/shared/util/DateUtil.java index b1e3d4a..28142c4 100644 --- a/util/src/main/java/de/muehlencord/shared/util/DateUtil.java +++ b/util/src/main/java/de/muehlencord/shared/util/DateUtil.java @@ -1,18 +1,35 @@ -package de.muehlencord.shared.util; - -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.util.Date; - -/** - * - * @author joern@muehlencord.de - */ -public class DateUtil { - - public static Date getCurrentTimeInUTC() { - ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC); - return Date.from(utc.toInstant()); - } - -} +package de.muehlencord.shared.util; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Date; + +/** + * + * @author joern@muehlencord.de + */ +public class DateUtil { + + public static Date getCurrentTimeInUTC() { + ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC); + return Date.from(utc.toInstant()); + } + + public static Date getDate(final LocalDate localDate) { + return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); + } + + public static LocalDate getDate(final Date date) { + if (date == null) + return null; + // ensure to call toInstant on java.util.Date and not on java.sql.Date because this will throw an UnsupportedOperationException + // see Java doc of java.sql.Date.toInstant() + Instant instant = new java.util.Date(date.getTime()).toInstant(); + ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault()); + return zdt.toLocalDate(); + } + +}