在没有使用Java8之前在封装相关时间工具类的时候都使用的是java.util.Calendar。
Java.util.Calendar类将日期同时存储为与标准纪元之间的偏移量以及一组日历字段。此双精度表示导致在意外的时间重新计算日历字段,从而产生不可预测的性能特点,java.util.Calendar是可改变的。也就是说明java.util.Calendar类是线程不安全的。在Java8中推出了新的日期类,而且是线程安全的,所以我们使用时间相关的类时,尽可能去使用Java8中,以避免存在的潜在问题。
下面是小编最近在工作过程中利用Java8中LocalDate,LocalDateTime相关类封装的关于时间获取的方法,希望对大家有所帮助。
public enum EConstantType{
NO(0, "开始时间"),
YES(1, "结束时间");
private int value;
private String message;
EConstantType(int value, String message) {
this.value = value;
this.message = message;
}
@Override
public int getValue() {
return value;
}
@Override
public String getExpr() {
return message;
}
}
public class DateUtils {
public static LocalTime firstTime = LocalTime.of(00, 00, 00);
public static LocalTime endTime = LocalTime.of(23, 59, 59);
/**
* 获取某个小时的开始时间和结束时间
*
* @param offset 0当前,1下一个小时,-1上一个小时,依次类推
* @return
*/
public static Map<Integer, LocalDateTime> getHourRange(int offset) {
LocalDateTime localDateTime = LocalDateTime.now().plusHours(offset);
LocalDate localDate = LocalDate.now();
int hour = localDateTime.getHour();
LocalTime first = LocalTime.of(hour, 00, 00);
LocalTime end = LocalTime.of(hour, 59, 59);
Map<Integer,LocalDateTime> map = Maps.newHashMap();
map.put(EConstantType.NO.getValue(), LocalDateTime.of(localDate, first));
map.put(EConstantType.YES.getValue(), LocalDateTime.of(localDate, end));
return map;
}
/**
* 获取某天的开始时间和结束时间
*
* @param offset 0今天,1明天,-1昨天,依次类推
* @return
*/
public static Map<Integer, LocalDateTime> getDayRange(int offset) {
LocalDate localDate = LocalDate.now().plusDays(offset);
Map<Integer, LocalDateTime> map = Maps.newHashMap();
map.put(EConstantType.NO.getValue(), LocalDateTime.of(localDate, firstTime));
map.put(EConstantType.YES.getValue(), LocalDateTime.of(localDate, endTime));
return map;
}
/**
* 获取某个星期的开始时间和结束时间
*
* @param offset 0 本周 1 下一周 -1 上一周 以此类推
* @return
*/
public static Map<Integer, LocalDateTime> getWeekRange(int offset) {
LocalDate monDay = LocalDate.now().plusWeeks(offset).with(DayOfWeek.MONDAY);
LocalDate sunDay = LocalDate.now().plusWeeks(offset).with(DayOfWeek.SUNDAY);
Map<Integer, LocalDateTime> map = Maps.newHashMap();
map.put(EConstantType.NO.getValue(), LocalDateTime.of(monDay, firstTime));
map.put(EConstantType.YES.getValue(), LocalDateTime.of(sunDay, endTime));
return map;
}
/**
* 获取某个月的开始时间和结束时间
*
* @param offset 0 本月 1 下一月 -1 上一月 以此类推
* @return
*/
public static Map<Integer, LocalDateTime> getMonthRange(int offset) {
LocalDate firstDay = LocalDate.now().plusMonths(offset).with(TemporalAdjusters.firstDayOfMonth());
LocalDate endDay = LocalDate.now().plusMonths(offset).with(TemporalAdjusters.lastDayOfMonth());
Map<Integer, LocalDateTime> map = Maps.newHashMap();
map.put(EConstantType.NO.getValue(), LocalDateTime.of(firstDay, firstTime));
map.put(EConstantType.YES.getValue(), LocalDateTime.of(endDay, endTime));
return map;
}
}
以后遇到的时间工具类的内容会逐步更新,欢迎大家在评论中一起完善。