开始使用 java8 的日期工具类

时间:2023-07-04 18:42:01

例如,现有的类(例如java.util.Date和SimpleDateFormatter)不是线程安全的,这会导致用户潜在的并发问题。而新的LocalDate、LocalDateTime、DateTimeFormatter是不可变值类。

LocalDate和LocalTime。它们是本地的,它们从观察者的角度表示日期和时间,例如书桌上的日历或墙上的时钟。还有一种称为复合类LocalDateTime,这是一个配对LocalDate和LocalTime。

下面是一个简单的思维导图和一个基于LocalDate、LocalDateTime...实现的日期工具类可以帮助我们记住一些类、API...,日期工具类中引入了gvava工具包。maven依赖如下

<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.1-jre</version>
</dependency>
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.*;
import java.util.*;

public class Date8Util {
private static final Logger logger = LoggerFactory.getLogger(Date8Util.class);
public static final HashMap<String,String> fomatMap = new HashMap();
static {
fomatMap.put("DATE_FORMAT_DEFAULT","yyyy-MM-dd HH:mm:ss");
fomatMap.put("FORMATE1","yyyy-MM-dd hh:mm:ss");
fomatMap.put("DATE_FORMAT_YYYYMMDD","yyyy-MM-dd");
fomatMap.put("DATE_FORMAT_YYYYMMDDHHSSMS","yyyyMMddHHmmssms");
fomatMap.put("DATE_FORMAT_YYYYMMDDHHSS","yyyyMMddHHmmss");
fomatMap.put("DATE_FORMAT_YYYY_MM_DD","yyyyMMdd");
fomatMap.put("DATE_FORMAT_YYYY_MM","yyyyMM");
fomatMap.put("DATE_FORMAT_HHmmss","HHmmss");
fomatMap.put("DATE_FORMAT_JQUERY_DATEPICKER_DEFAULT","yyyy/MM/dd");
fomatMap.put("FORMATE_PATTERN_C_YYYYMMDD","yyyy年MM月dd日");
fomatMap.put("FORMATE_PATTERN_C_MMDD","MM月dd日");
fomatMap.put("FORMATE_PATTERN_C_YYYYMM","yyyy年MM月");
}
/**
* 获取当前日期时间 yyyy-MM-dd HH:mm:ss
* @return
*/
public static String getTime(){
LocalDateTime date = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(fomatMap.get("DATE_FORMAT_DEFAULT"), Locale.CHINA);
return date.format(dtf);
}

/**
* 当前日期 字符串日期格式
* @return Date
*/
public static Date getNowDate(){
return Timestamp.valueOf(getTime());
}

/**
* 当前日期.yyyy-MM-dd
* @return
*/
public static String getCurrentDate(){
return LocalDate.now().format(DateTimeFormatter.ofPattern(fomatMap.get("DATE_FORMAT_YYYYMMDD"), Locale.CHINA));
}

/**
* @Description 当前日期时间 yyyyMMddHHmmssms
* @return
*/
public static String getCurrDate(){
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(fomatMap.get("DATE_FORMAT_YYYYMMDDHHSSMS"), Locale.CHINA));
}
public static String getNowDate(String fomat){
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(fomat,Locale.CHINA));
}

/**
* 字符串转日期
* @param aMask
* @param aDate
* @return
*/
public static String convertDateToString(String aMask, Date aDate){
//Date 转化位 LocalDateTime
LocalDateTime dateTime = LocalDateTime.ofInstant(aDate.toInstant(),ZoneId.systemDefault());
return getDateTime(aMask, dateTime);
}
public static String convertDateToString(String aMask, LocalDateTime dateTime){
return getDateTime(aMask, dateTime);
}

/**
* 获取date time
* @param fmt
* @param dateTime
* @return
*/
private static String getDateTime(String fmt, LocalDateTime dateTime) {
DateTimeFormatter dtf = null;
String str = "";
if(dateTime != null){
dtf = DateTimeFormatter.ofPattern(fmt,Locale.CHINA);
str = dateTime.format(dtf);
}
return str;
}

/**
* 日期字符串转 日期
* @param fmt
* @param dateStr
* @return
*/
public static LocalDate convertStringToDate(String fmt,String dateStr){
if (Strings.isNullOrEmpty(fmt) || Strings.isNullOrEmpty(dateStr)) {
return null;
} else {
DateTimeFormatter sdf = DateTimeFormatter.ofPattern(fmt,Locale.CHINA);
try {
return LocalDate.parse(dateStr,sdf);
} catch (DateTimeParseException var4) {
logger.error("ParseException[" + fmt + "] for:" + dateStr, var4);
return null;
}
}
}

/**
* 获取 日期所在月份的第一天 date为空传当前月
* @param date
* @return
*/
public static LocalDate getFirstDayOfMonth(LocalDate date){
return Optional.ofNullable(date).map(dt -> dt.with(TemporalAdjusters.firstDayOfMonth())).orElse(null);
}
/**
* 获取 日期所在月份的最后一天,date为空传当前月
* @param date
* @return
*/
public static LocalDate getLastDayOfMonth(LocalDate date){
return Optional.ofNullable(date).map(dt -> dt.with(TemporalAdjusters.lastDayOfMonth())).orElse(null);
}

/**
* 获取上一个月的这个时候,例如当前日期2002-09-11,则返回2020-08-11
* @param date
* @return
*/
public static LocalDate getMonthOfMonth(LocalDate date){
return Optional.ofNullable(date).map(dt -> dt.minusMonths(1)).orElse(null);
}

/**
* 获取系统日期时间
* @return
*/
public static LocalDateTime getSystemTime(){
return LocalDateTime.ofInstant(Instant.now(),ZoneId.systemDefault());
}

/**
* 日期时间 转字符串
* @param dateTime
* @param pattern
* @return
*/
public static String dateTimeToString(LocalDateTime dateTime, String pattern){
if(dateTime == null || Strings.isNullOrEmpty(pattern)){
return null;
}
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern,Locale.CHINA);
return dateTime.format(dtf);
}

/**
* 两个日期相隔的天数
* @param startdate
* @param endDate
* @return
*/
public static int daysOfTwo(LocalDate startdate, LocalDate endDate){
return (int) startdate.until(endDate, ChronoUnit.DAYS);
}
public static int daysOfTwo(String startdate, String endDate, String dateFormat){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat,Locale.CHINA);
LocalDate smDate = LocalDate.parse(startdate,dtf);
LocalDate bDate = LocalDate.parse(endDate,dtf);
return (int)smDate.until(bDate,ChronoUnit.DAYS);
}

/**
* 昨天日期
* @return
*/
public static String getYesterday(){
LocalDate now = LocalDate.now();
return now.minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd",Locale.CHINA));
}

/**
* 比较日期大小
* @param date1
* @param date2
* @return
*/
public static int compare(String date1, String date2){
DateTimeFormatter dtf = null;
if(date1.indexOf(":") > -1 && date2.indexOf(":") > -1){
dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss",Locale.CHINA);
LocalDateTime dateTime1 = LocalDateTime.parse(date1,dtf);
LocalDateTime dateTime2 = LocalDateTime.parse(date2,dtf);
if(dateTime1.isBefore(dateTime2)){
return -1;
}
return dateTime1.isAfter(dateTime2) ? 1:0;
}else{
dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd",Locale.CHINA);
LocalDate dt1 = LocalDate.parse(date1,dtf);
LocalDate dt2 = LocalDate.parse(date2,dtf);
if(dt1.isBefore(dt2)){
return -1;
}
return dt1.isAfter(dt2) ? 1:0;
}
}

/**
* 获取日期 x年x月x日
* @param date
* @return
*/
public static String getFormatDate(String date){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.parse(date,dtf2);
return localDate.format(dtf);
}

/**
* data1 是否 大于date2
* @param date1
* @param date2
* @param format
* @return
*/
public static boolean date1DYdate2NY(String date1, String date2, String format){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format,Locale.CHINA);
LocalDate dt1 = LocalDate.parse(date1,dtf);
LocalDate dt2 = LocalDate.parse(date2,dtf);
return dt1.isAfter(dt2);
}

public static String getTimeYYYYMMDD() {
DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyyMMdd",Locale.CHINA);
return LocalDate.now().format(sdf);
}

public static String getTimeHHmmss() {
DateTimeFormatter sdf = DateTimeFormatter.ofPattern("HHmmss",Locale.CHINA);
return LocalTime.now().format(sdf);
}

public static String getTimeHHmmss000() {
DateTimeFormatter sdf = DateTimeFormatter.ofPattern("HHmmss000",Locale.CHINA);
return LocalTime.now().format(sdf);
}
public static LocalDateTime changeMonth(LocalDateTime date, int i) {
return date.minusMonths(i);
}

public static String changeMonth(int month, String format) {
LocalDateTime dateTime = changeMonth(LocalDateTime.now(),month);
return dateToString(getFirstDayOfMonth(dateTime.toLocalDate()), format);
}

private static String dateToString(LocalDate date, String format) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format,Locale.CHINA);
return date.format(dtf);
}

/**
* 获取上年第一天
* @param format
* @param year
* @return
*/
public static String getFirstDayOfPastYear(String format, int year) {
LocalDateTime dateTime = LocalDateTime.now().minusYears(year);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format,Locale.CHINA);
String sdate = dateTime.with(TemporalAdjusters.firstDayOfYear()).format(dtf) ;
return sdate;
}

public static String getFirstDayOfLastYear(String format) {
return getFirstDayOfPastYear(format, 1);
}

/**
* 获取上x年的的最后一天
* @param format
* @param year
* @return
*/
public static String getLastDayOfPastYear(String format, int year) {
LocalDateTime dateTime = LocalDateTime.now().minusYears(year);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format,Locale.CHINA);
String sdate = dateTime.with(TemporalAdjusters.lastDayOfYear()).format(dtf) ;
return sdate;
}

/**
* 获取上1年的的最后一天
* @param format
* @return
*/
public static String getLastDayOfLastYear(String format) {
return getLastDayOfPastYear(format, 1);
}

/**
* 当前月 + month 的第一天
* @param month
* @return
*/
public static String getFirstDayOfMonth(int month) {
LocalDate localDate = LocalDate.now().minusMonths(-month);
LocalDate day = localDate.with(TemporalAdjusters.firstDayOfMonth());
return dateToString(getFirstDayOfMonth(day), "yyyy-MM-dd");
}
/**
* 当前年+year , 月 + month 的第一天
* @param month
* @return
*/
public static String getFirstDayOfMonth(int month, int year) {
LocalDate localDate = LocalDate.now().minusYears(-year).minusMonths(-month);
LocalDate day = localDate.with(TemporalAdjusters.firstDayOfMonth());
return dateToString(getFirstDayOfMonth(day), "yyyy-MM-dd");
}
public static boolean isMonthEnd(LocalDate date){
LocalDate day = date.with(TemporalAdjusters.lastDayOfMonth());
if(date.equals(day)){
return true;
}
return false;
}
public static boolean isFirstDayOfMonth(String date){
LocalDate dt = convertStringToDate("yyyy-MM-dd",date);
return Strings.isNullOrEmpty(date) ? false : dt.equals(dt.with(TemporalAdjusters.firstDayOfMonth()));
}
public static LocalDate getFirstDayOfWeek(LocalDate date){
TemporalField fieldISO = WeekFields.ISO.dayOfWeek();
return date.with(fieldISO,1);
}
}

开始使用 java8 的日期工具类