From 6ed9a927ac1ef8557e6121b22c295e87161d7811 Mon Sep 17 00:00:00 2001 From: johnniang Date: Mon, 29 Apr 2019 17:06:14 +0800 Subject: [PATCH] Add add method in DateUtils --- .../app/config/properties/HaloProperties.java | 1 + .../java/run/halo/app/utils/DateUtils.java | 47 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/main/java/run/halo/app/config/properties/HaloProperties.java b/src/main/java/run/halo/app/config/properties/HaloProperties.java index b61872a15..719475a5c 100644 --- a/src/main/java/run/halo/app/config/properties/HaloProperties.java +++ b/src/main/java/run/halo/app/config/properties/HaloProperties.java @@ -38,6 +38,7 @@ public class HaloProperties { private String workDir = HaloConst.USER_HOME + "/.halo/"; public HaloProperties() throws IOException { + // Create work directory if not exist Files.createDirectories(Paths.get(workDir)); } } diff --git a/src/main/java/run/halo/app/utils/DateUtils.java b/src/main/java/run/halo/app/utils/DateUtils.java index bac8b3c61..675217984 100644 --- a/src/main/java/run/halo/app/utils/DateUtils.java +++ b/src/main/java/run/halo/app/utils/DateUtils.java @@ -5,6 +5,7 @@ import org.springframework.util.Assert; import java.util.Calendar; import java.util.Date; +import java.util.concurrent.TimeUnit; /** * Date utilities. @@ -41,4 +42,50 @@ public class DateUtils { calendar.setTime(date); return calendar; } + + /** + * Adds date. + * + * @param date current date must not be null + * @param time time must not be less than 1 + * @param timeUnit time unit must not be null + * @return added date + */ + public static Date add(@NonNull Date date, long time, @NonNull TimeUnit timeUnit) { + Assert.notNull(date, "Date must not be null"); + Assert.isTrue(time >= 0, "Addition time must not be less than 1"); + Assert.notNull(timeUnit, "Time unit must not be null"); + + Date result; + + int timeIntValue; + + if (time > Integer.MAX_VALUE) { + timeIntValue = Integer.MAX_VALUE; + } else { + timeIntValue = Long.valueOf(time).intValue(); + } + + // Calc the expiry time + switch (timeUnit) { + case DAYS: + result = org.apache.commons.lang3.time.DateUtils.addDays(date, timeIntValue); + break; + case HOURS: + result = org.apache.commons.lang3.time.DateUtils.addHours(date, timeIntValue); + break; + case MINUTES: + result = org.apache.commons.lang3.time.DateUtils.addMinutes(date, timeIntValue); + break; + case SECONDS: + result = org.apache.commons.lang3.time.DateUtils.addSeconds(date, timeIntValue); + break; + case MILLISECONDS: + result = org.apache.commons.lang3.time.DateUtils.addMilliseconds(date, timeIntValue); + break; + default: + result = date; + } + return result; + } }