使用Java8新的时间api重构时间工具类
package com.chehejia.osd.server.util;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
public class LocalDateUtils {
public static Integer currentTs() {
return (int) LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours(8));
}
public static String currentDate(String format) {
return formatTs(currentTs(), format);
}
public static String formatTs(Integer ts, String format) {
return toLocalDateTime(ts).format(DateTimeFormatter.ofPattern(format));
}
public static LocalDateTime toLocalDateTime(Integer ts) {
return LocalDateTime.ofEpochSecond(ts, 0, ZoneOffset.ofHours(8));
}
public static Integer toTs(LocalDateTime localDateTime) {
return (int) localDateTime.toEpochSecond(ZoneOffset.ofHours(8));
}
public static Integer toDayStartTs(Integer ts) {
LocalDateTime oldLocalDateTime = toLocalDateTime(ts);
LocalDateTime newLocalDateTime = LocalDateTime.of(oldLocalDateTime.toLocalDate(), LocalTime.MIN);
return toTs(newLocalDateTime);
}
public static Integer toDayEndTs(Integer ts) {
LocalDateTime oldLocalDateTime = toLocalDateTime(ts);
LocalDateTime newLocalDateTime = LocalDateTime.of(oldLocalDateTime.toLocalDate(), LocalTime.MAX);
return toTs(newLocalDateTime);
}
public static Integer toLastDayStartTs(Integer ts) {
LocalDateTime oldLocalDateTime = toLocalDateTime(ts);
LocalDateTime newLocalDateTime = LocalDateTime.of(oldLocalDateTime.toLocalDate().plusDays(-1), LocalTime.MIN);
return toTs(newLocalDateTime);
}
public static Integer toLastDayEndTs(Integer ts) {
LocalDateTime oldLocalDateTime = toLocalDateTime(ts);
LocalDateTime newLocalDateTime = LocalDateTime.of(oldLocalDateTime.toLocalDate().plusDays(-1), LocalTime.MAX);
return toTs(newLocalDateTime);
}
public static Integer toFirstDayOfMonth(Integer ts) {
LocalDateTime oldLocalDateTime = toLocalDateTime(ts);
LocalDateTime newLocalDateTime = oldLocalDateTime.with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
return toTs(newLocalDateTime);
}
public static Integer toLastDayOfMonth(Integer ts) {
LocalDateTime oldLocalDateTime = toLocalDateTime(ts);
LocalDateTime newLocalDateTime = oldLocalDateTime.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);
return toTs(newLocalDateTime);
}
public static Integer dateToTs(String date, String format) {
LocalDateTime localDateTime = LocalDateTime.parse(date, DateTimeFormatter.ofPattern(format));
return toTs(localDateTime);
}
public static Integer toLastSundayEndTs(Integer ts) {
LocalDateTime oldLocalDateTime = toLocalDateTime(ts);
LocalDateTime newLocalDateTime = oldLocalDateTime.minusWeeks(1L).with(DayOfWeek.SUNDAY).with(LocalTime.MAX);
return toTs(newLocalDateTime);
}
}