一锉走、問題描述
jdk8以前的Date、Calender類术徊,處理轉(zhuǎn)換繁瑣本刽,線程不安全
二、解決
jdk8使用LocalDate赠涮、LocalTime子寓、LocalDateTime來處理日期和時(shí)間問題。
LocalDate 本地日期笋除;LocalTime 本地時(shí)間斜友;LocalDateTime 本地日期+時(shí)間
日期時(shí)間工具類:
package com.cebbank.cloudmall.controller;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalUnit;
/**
* 日期時(shí)間工具類
*/
public class LocalDateTimeUtils {
/**
* 日期字符串按照指定pattern轉(zhuǎn)換為LocalDateTime
* @param dateTimeStr
* @param pattern
* @return
*/
public static LocalDateTimeconverStrToLocalDateTime(String dateTimeStr,String pattern){
return LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern(pattern));
}
/**
* LocalDateTime按照指定pattern轉(zhuǎn)為字符串
* @param localDateTime
* @param pattern
* @return
*/
public static StringconvertDateTimeToStr(LocalDateTime localDateTime,String pattern){
return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
}
/**
* 按照指定pattern獲取當(dāng)前時(shí)間字符串
* @param pattern
* @return
*/
public static StringgetCurrentDateTime(String pattern){
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(pattern));
}
/**
* 將一種格式的日期字符串轉(zhuǎn)換為另一種格式
* @param dateTimeStr
* @param fromPattern
* @param toPattern
* @return
*/
public static StringconvertDateTimeStrByPattern(String dateTimeStr,String fromPattern,String toPattern){
return LocalDateTime.parse(dateTimeStr,DateTimeFormatter.ofPattern(fromPattern)).format(DateTimeFormatter.ofPattern(toPattern));
}
/**
* 判斷是否在某一時(shí)間段內(nèi)
* @param nowTime
* @param startTime
* @param endTime
* @return
*/
public static boolean betweenDateTime(LocalDateTime nowTime,LocalDateTime startTime,LocalDateTime endTime){
return nowTime.isAfter(startTime) && nowTime.isBefore(endTime);
}
/**
* 返回當(dāng)前日期零點(diǎn)
* @return
*/
public static LocalDateTimegetZeroDateTime(){
return LocalDateTime.now().toLocalDate().atTime(0,0,0,0);
}
/**
* 獲取當(dāng)前時(shí)間前后的時(shí)間
* @param dateTime
* @param type
* @param num
* @return
*/
public static LocalDateTimegetDateTime(LocalDateTime dateTime, TemporalUnit type,int num){
return dateTime.plus(num,type);
}
/**
* 獲取兩個(gè)時(shí)間的間隔天數(shù)(過了零點(diǎn)即算一天)
* @param begin
* @param end
* @return
*/
public static int getDaysBetweenTowDateTime(LocalDateTime begin,LocalDateTime end){
return begin.toLocalDate().until(end.toLocalDate()).getDays();
}
}