Java8日期时间类使用

一、Date类

Data·类表示特定的瞬间,精确到毫秒,它是java.util·包下的类,用之前需要先导包

1.1 时区

GMT(Greenwich Mean Time)代表格林尼治标准时间,而CST却同时可以代表如下4个不同的时区:
   Central Standard Time (USA) UT-6:00
   Central Standard Time (Australia) UT+9:30
   China Standard Time UT+8:00
   Cuba Standard Time UT-4:00

1.2 基本使用

1.2.1 初始化

Date date = new Date();
Date date1 = new Date(1000L);
// 默认创建一个本地时间, long类型
// Date date = new Date(System.currentTimeMillis());
// 从1970-1-1 0:0:0开始

1.2.2 输出时间

System.out.println(date1);
// 输出北京时间:Thu Jan 01 08:00:01 CST 1970
System.out.println(date1.toGMTString());
// 输出格林标准时间:1 Jan 1970 00:00:01 GMT

1.2.3 输出时差

// 返回与格林时间的时差, 以分钟计时, 正好是8个小时, 此函数输出-480   则北京时间-480分钟等于格林时间
date1.getTimezoneOffset();

1.2.4 打印毫秒数

long m = date1.getTime();
// 打印出date到1970年1月1日的毫秒数
System.out.println("m = " + m);

1.2.5 比较时间

// 比较时间
// 返回boolean类型
date.after(date1);
date.before(date1);
// 返回-1 1 0
date.compareTo(date1);

1.3 Date类的子类

1.3.1 Date的使用

// sql包的date类, 接收一个毫秒值
java.sql.Date sqldate = new java.sql.Date(1000L);
// 输出一个这样的字符串 1970-01-01
System.out.println(sqldate);
// 转换成格林时间和util中date输出一样
System.out.println(sqldate.toGMTString());

1.3.2 Timestamp使用

java.sql.Timestamp timestamp = new Timestamp(2000L);
// 返回的均为本地时间
//1970-01-01 08:00:02.0
//1970-01-01T08:00:02
System.out.println(timestamp);
System.out.println(timestamp.toLocalDateTime());

// 返回一个格林瞬时时间
// 1970-01-01T00:00:02Z
System.out.println(timestamp.toInstant());

1.3.3 Time使用

java.sql.Time time = new Time(3000L);
// 返回一个不带日期的本地时间  08:00:03
System.out.println(time);

1.4 SimpleDateFormat使用

Date date = new Date();
// 指定格式输出时间
/* yyyy 年
   MM   月
   dd   日
   hh   12小时制
   HH   24小时制0-23
   mm   分
   ss   秒
   SSS  毫秒
*/
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
System.out.println(dateFormat.format(date));

// 将指定格式的字符串转化成Date
// "2018-05-26 09:03:22.658"
DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
try {
    date = dateFormat1.parse("2018-05-26 09:03:22.658");
    // 输出:date = Sat May 26 09:03:22 CST 2018
    System.out.println("date = " + date);
} catch (ParseException e) {
    e.printStackTrace();
}

SimpleDateFormat是线程不安全的类,一般不要定义为static变量,如果定义为static,必须加锁,或者使用DateUtils工具类。
正例:注意线程安全,使用DateUtils。亦推荐如下处理:

private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
    @Override
    protected DateFormat initialValue() {
        return new SimpleDateFormat("yyyy-MM-dd");
    }
};

1.5 Calender使用

Calendar类的功能要比Date类强大很多,而且在实现方式上也比Date类要复杂一些。

Calendar类是一个抽象类,在实际使用时实现特定的子类的对象,只需要使用getInstance方法创建即可。

Java官方推荐使用Calendar来替换Date的使用。

//Calendar类实现了公历日历,GregorianCalendar是Calendar类的一个具体实现。
//Calendar的getInstance()方法返回一个默认用当前的语言环境和时区初始化的GregorianCalendar对象。
Calendar calendar = new GregorianCalendar();

// 设置日历时间
calendar.set(Calendar.YEAR, 2019);
calendar.set(Calendar.MONTH, 5);
calendar.set(Calendar.DAY_OF_MONTH, 26);

//使用Date类设置calendar时间
calendar.setTime(new Date());

//取得日历时间 calendar.getTime();  返回一个Date对象
// 输出:Wed Jun 26 12:58:42 CST 2019
System.out.println(calendar.getTime().toString());

//使用日历取得时间偏移
// 输出:Tue Jun 26 12:58:42 CST 2029
calendar.add(Calendar.YEAR, 10);
System.out.println(calendar.getTime().toString());

二、java8时间处理

Java处理日期、日历和时间的不足之处:将java.util.Date设定为可变类型,以及SimpleDateFormat的非线程安全使其应用非常受限。

Java 8推出了全新的日期时间API。不同于老版本,新API基于ISO标准日历系统,java.time包下的所有类都是不可变类型而且线程安全。

ZoneId:时区ID,用来确定InstantLocalDateTime互相转换的规则。
Instant:瞬时实例,用来表示时间线上的一个点(瞬时)。
LocalDate:表示没有时区的日期, 不包含具体时间,LocalDate是不可变并且线程安全的。
LocalTime:表示没有时区的时间, 不包含日期,LocalTime是不可变并且线程安全的。
LocalDateTime:表示没有时区的日期时间,组合了日期和时间,LocalDateTime是不可变并且线程安全的。
ZonedDateTime:最完整的日期时间,包含时区和相对UTC或格林威治的时差。
Clock:用于访问当前时刻、日期、时间,用到时区。
Duration:用秒和纳秒表示时间的数量(长短),用于计算两个日期的“时间”间隔。
Period:用于计算两个“日期”间隔。
TemporalAccessorLocalDateTimeLocalDateLocalTime等类的顶级接口。

其中,LocalDateLocalTimeLocalDateTime是新API里的基础对象。新API还引入了ZoneOffSetZoneId类,使得解决时区问题更为简便。解析、格式化时间的DateTimeFormatter类也全部重新设计。

说明:如果是JDK8的应用,可以使用Instant代替Date,LocalDateTime代替Calendar,DateTimeFormatter代替SimpleDateFormat,官方给出的解释:simple beautiful strong immutable thread-safe。

2.1 常用方法使用

2.1.1 获取当前时间

/**
 * 获取当前时间
 */
public void localDateCreate() {

    LocalDate localDate = LocalDate.now();
    LocalTime localTime = LocalTime.now();
    LocalDateTime localDateTime = LocalDateTime.now();
    System.out.println("年月日: " + localDate);
    System.out.println("时分秒毫秒: " + localTime);
    System.out.println("年月日时分秒毫秒: " + localDateTime);

    /*输出:
        年月日: 2020-10-16
        时分秒毫秒: 09:55:49.448
        年月日时分秒毫秒: 2020-10-16T09:55:49.448
    */
}

2.1.2 获取日期(年月日周时分秒)

/**
 * 获取日期的年月日周时分秒
 */
public void getDateInfo() {
    LocalDateTime localDateTime = LocalDateTime.now();
    //本年当中第多少天
    int dayOfYear = localDateTime.getDayOfYear();
    //本月当中第多少天
    int dayOfMonth = localDateTime.getDayOfMonth();
    //本周中星期几(英文)
    DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
    //本周中星期几(数字)
    int value = dayOfWeek.getValue();
    //本周中星期几(汉字)
    String dayOfWeekCN = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.CHINA);
    //当天开始时间
    LocalDateTime minTime = LocalDateTime.of(localDateTime, LocalTime.MIN);
    //当天结束时间
    LocalDateTime maxTime = LocalDateTime.of(localDateTime, LocalTime.MAX);
    System.out.println("今天是" + localDateTime + "\n"
            + "本年当中第" + dayOfYear + "天" + "\n"
            + "本月当中第" + dayOfMonth + "天" + "\n"
            + "本周中星期" + value + "-即" + dayOfWeek + "-即" + dayOfWeekCN + "\n");    
    
    int year = localDateTime.getYear();              //年
    Month month = localDateTime.getMonth();          //月
    int monthValue = localDateTime.getMonthValue();  //直接获取
    int dayOfMonth1 = localDateTime.getDayOfMonth(); //日
    int hour = localDateTime.getHour();              //时   
    int minute = localDateTime.getMinute();          //分  
    int second = localDateTime.getSecond();          //秒
    int nano = localDateTime.getNano();              //纳秒

    System.out.println("今天是" + localDateTime + "\n"
            + "年: " + year + "\n"
            + "月: " + monthValue + "-即 " + month + "\n"
            + "日: " + dayOfMonth1 + "\n"
            + "时: " + hour + "\n"
            + "分: " + minute + "\n"
            + "秒: " + second + "\n"
            + "纳秒: " + nano + "\n"
    );
}

2.1.3 设置自定义日期

/**
 * 设置自定义日期
 */
public void setDate() {
    LocalDate localDate = LocalDate.of(2020, 10, 15);
    LocalTime localTime = LocalTime.of(10, 10, 10);
    LocalDateTime localDateTime = LocalDateTime.of(2020, 10, 15, 10, 10);
    System.out.println("自定义的年月日: " + localDate);
    System.out.println("自定义时分秒毫秒: " + localTime);
    System.out.println("自定义年月日时分秒毫秒: " + localDateTime);

    /*输出:
        自定义的年月日: 2020-10-15
        自定义时分秒毫秒: 10:10:10
        自定义年月日时分秒毫秒: 2020-10-15T10:10
    */
}

2.1.4 日期时间的加减

/**
 * 日期时间的加减
 */
public void lessOrAddDate() {

    System.out.println("######################### >>> LocalDate <<< #########################");
	
    LocalDate localDate = LocalDate.now();
    System.out.println("当前时间: " + localDate);

    System.out.println("*********添加 操作*********");	
    LocalDate addOneDay = localDate.plusDays(1L); //添加一日
    LocalDate addOneMonths = localDate.plusMonths(1L);//添加一月
    LocalDate addOneYears = localDate.plusYears(1L);//添加一年
    LocalDate addOneWeeks = localDate.plusWeeks(1L);//添加一周

    System.out.println("添加一日: " + addOneDay);
    System.out.println("添加一月: " + addOneMonths);
    System.out.println("添加一年: " + addOneYears);
    System.out.println("添加一周: " + addOneWeeks);

    System.out.println("*********减 操作*********");
    LocalDate delOneDay = localDate.minusDays(1L); //减去一日
    LocalDate delOneMonths = localDate.minusMonths(1L);//减去一月
    LocalDate delOneYears = localDate.minusYears(1L);//减去一年
    LocalDate delOneWeeks = localDate.minusWeeks(1L);//减去一周

    System.out.println("减去一日: " + delOneDay);
    System.out.println("减去一月: " + delOneMonths);
    System.out.println("减去一年: " + delOneYears);
    System.out.println("减去一周: " + delOneWeeks);
    
    System.out.println("######################### >>> LocalTime <<< #########################");
    
    LocalTime localTime = LocalTime.now();
    System.out.println("当前时间: " + localTime);

    System.out.println("*********添加 操作*********");	
    LocalTime addOneHours = localTime.plusHours(1L); //添加1小时
    LocalTime addOneMinutes = localTime.plusMinutes(1L);//添加1分钟
    LocalTime addOneSeconds = localTime.plusSeconds(1L);//添加1秒
    LocalTime addOneNanos = localTime.plusNanos(1L);//添加1纳秒

    System.out.println("添加1小时: " + addOneHours);
    System.out.println("添加1分钟: " + addOneMinutes);
    System.out.println("添加1秒: " + addOneSeconds);
    System.out.println("添加1纳秒: " + addOneNanos);
	
    System.out.println("*********减 操作*********");  	
    LocalTime delOneHours = localTime.minusHours(1L); //减去1小时
    LocalTime delOneMinutes = localTime.minusMinutes(1L);//减去1分钟
    LocalTime delOneSeconds = localTime.minusSeconds(1L);//减去1秒
    LocalTime delOneNanos = localTime.minusNanos(1L);//减去1纳秒

    System.out.println("减去1小时: " + delOneHours);
    System.out.println("减去1分钟: " + delOneMinutes);
    System.out.println("减去1秒: " + delOneSeconds);
    System.out.println("减去1纳秒: " + delOneNanos);

    /*
    输出:
        ######################### >>> LocalDate <<< #########################	
        当前时间: 2020-10-16

        *********添加 操作*********
        添加一日: 2020-10-17
        添加一月: 2020-11-16
        添加一年: 2021-10-16
        添加一周: 2020-10-23

        *********减 操作*********
        减去一日: 2020-10-15
        减去一月: 2020-09-16
        减去一年: 2019-10-16
        减去一周: 2020-10-09

        ######################### >>> LocalTime <<< #########################
        当前时间: 10:20:22.164

        *********添加 操作*********
        添加1小时: 11:20:22.164
        添加1分钟: 10:21:22.164
        添加1秒: 10:20:23.164
        添加1纳秒: 10:20:22.164000001

        *********减 操作*********
        减去1小时: 09:20:22.164
        减去1分钟: 10:19:22.164
        减去1秒: 10:20:21.164
        减去1纳秒: 10:20:22.163999999
     */
}

LocalDateTime满足以上所有LocalDateLocalTime的操作日期时间方法。方法名称和LocalDateLocalTime也都相同。

2.1.5 计算时间日期间隔

/**
 * 计算时间日期间隔
 * <p>
 * Duration: 用于计算两个“时间”间隔
 * Period: 用于计算两个“日期”间隔
 */
public void durationOrPeriod() {
    LocalDateTime now = LocalDateTime.now();
    System.out.println("duration当前时间:" + now);

    LocalDateTime of = LocalDateTime.of(2020, 10, 15, 10, 24);
    System.out.println("duration自定义时间:" + of);

    //Duration:用于计算两个“时间”间隔
    Duration duration = Duration.between(now, of);

    System.out.println(now + " 与 " + of + " 间隔  " + "\n"
            + " 天 :" + duration.toDays() + "\n"
            + " 时 :" + duration.toHours() + "\n"
            + " 分 :" + duration.toMinutes() + "\n"
            + " 毫秒 :" + duration.toMillis() + "\n"
            + " 纳秒 :" + duration.toNanos() + "\n"
    );

    LocalDate nowDate = LocalDate.now();
    System.out.println("period当前时间:" + now);

    LocalDate ofDate = LocalDate.of(2020, 10, 15);
    System.out.println("period自定义时间:" + of);

    //Period:用于计算两个“日期”间隔
    Period period = Period.between(nowDate, ofDate);
    System.out.println("Period相差年数: " + period.getYears());
    System.out.println("Period相差月数: " + period.getMonths());
    System.out.println("Period相差日数: " + period.getDays());

    //还可以这样获取相差的年月日
    System.out.println("-------------------------------");

    long years = period.get(ChronoUnit.YEARS);
    long months = period.get(ChronoUnit.MONTHS);
    long days = period.get(ChronoUnit.DAYS);
    System.out.println("Period相差的年月日分别为 : " + years + "," + months + "," + days);

    //注意,当获取两个日期的间隔时,并不是单纯的年月日对应的数字相加减,而是会先算出具体差多少天,
    //    再折算成相差几年几月几日的

    /*
    输出:
        duration当前时间:2020-10-16T14:41:40.235
        duration自定义时间:2020-10-15T10:24
        2020-10-16T14:41:40.235 与 2020-10-15T10:24 间隔
         天 :-1
         时 :-28
         分 :-1697
         毫秒 :-101860235
         纳秒 :-101860235000000

        period当前时间:2020-10-16T14:41:40.235
        period自定义时间:2020-10-15T10:24
        Period相差年数 : 0
        Period相差月数 : 0
        Period相差日数 : -1
        -------------------------------
        Period相差的年月日分别为 : 0,0,-1
     */
}

2.1.6 修改时间值

/**
 * 将年、月、日等修改为指定的值,并返回新的日期(时间)对象
 * 析: 其效果与时间日期相加减差不多,如今天是2018-01-13,要想变为2018-01-20有两种方式
 * a. localDate.plusDays(20L) -> 相加指定的天数
 * b. localDate.withDayOfYear(20) -> 直接指定到哪一天
 */
public void directDesignationTime() {
    LocalDate localDate = LocalDate.now();
    System.out.println("当前时间: " + localDate);

    LocalDate addDay = localDate.plusDays(4);
    System.out.println("添加4天后的日期: " + addDay);

    LocalDate directDesignationDate = localDate.withDayOfMonth(20);
    System.out.println("直接指定到当月第几号: " + directDesignationDate);

    LocalDate directDesignationYearDate = localDate.withDayOfYear(20);
    System.out.println("直接指定到当年第几天: " + directDesignationYearDate);

    LocalDate directDesignationYear = localDate.withYear(2000);
    System.out.println("当前时间直接指定年份: " + directDesignationYear);

    LocalDate directDesignationMonth = localDate.withMonth(6);
    System.out.println("当前时间直接指定月份: " + directDesignationMonth);

    LocalTime localTime = LocalTime.now();
    LocalTime directDesignationHour = localTime.withHour(2);
    System.out.println("直接指定到小时: " + directDesignationHour);

    LocalTime directDesignationMinute = localTime.withMinute(2);
    System.out.println("直接指定到分钟: " + directDesignationMinute);
}

2.1.7 时间日期前后的比较与判断

/**
 * 时间日期前后的比较与判断
 */
public void isBefore() {
    LocalDate now = LocalDate.now();
    LocalDate of = LocalDate.of(2020, 10, 15);

    //判断of是否在now时间之前
    boolean before = of.isBefore(now);
    System.out.println("判断of是否在now时间之前:" + before);

    //判断of是否在now时间之后
    boolean after = of.isAfter(now);
    System.out.println("判断of是否在now时间之后:" + after);

    //判断两个时间是否相等
    boolean equal = of.isEqual(now);
    System.out.println("判断两个时间是否相等:" + equal);

    //判断是否为闰年
    boolean leapYear = now.isLeapYear();
    System.out.println("判断是否为闰年:" + leapYear);

    /*输出:
        判断of是否在now时间之前:true
        判断of是否在now时间之后:false
        判断两个时间是否相等:false
        判断是否为闰年:true
    */
}

2.1.8 时钟:clock()

/**
 * java8时钟:clock()
 */
public void clock() {
    //返回当前时间,根据系统时间和UTC
    Clock clock = Clock.systemUTC();
    System.out.println(clock);
    // 运行结果: SystemClock[Z]
}

2.1.9 时间戳

/**
 * 时间戳
 * 事实上Instant就是java8以前的Date,
 * 可以使用以下两个类中的方法在这两个类型之间进行转换,
 * 比如Date.from(Instant)就是用来把Instant转换成java.util.date的,
 * 而new Date().toInstant()就是将Date转换成Instant的
 */
public void instant() {
    Instant instant = Instant.now();
    System.out.println(instant);

    Date date = Date.from(instant);

    Instant instant2 = date.toInstant();
    System.out.println(date);
    System.out.println(instant2);

    /*输出:
        2022-05-21T08:30:07.177Z
        Sat May 21 16:30:07 CST 2022
        2022-05-21T08:30:07.177Z
    */
}

2.2 日期格式化

2.2.1 LocalDate转String

/**
 * 将时间对象转化为日期字符串
 * <p>
 * 时间日期的格式化(格式化后返回的类型是String) 
 * 自定格式使用DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS");
 * 注:自定义转化的格式一定要与日期类型对应
 * LocalDate只能设置仅含年月日的格式
 * LocalTime只能设置仅含时分秒的格式
 * LocalDateTime可以设置含年月日时分秒的格式
 */
public void formatter1() {
    LocalDateTime now = LocalDateTime.now();
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS");
    String format = dtf.format(now);
    System.out.println(format);

    //输出:2020-10-16 14:41:01:086
}

2.2.2 String转LocalDate

/**
 * 将时间字符串形式转化为日期对象
 * <p>
 * 注:格式的写法必须与字符串的形式一样
 * 2018-01-13 21:27:30 对应 yyyy-MM-dd HH:mm:ss
 * 20180113213328 对应 yyyyMMddHHmmss
 * 否则会报运行时异常!
 * <p>
 * 但要记住:得到的最终结果都是类似2018-01-13T21:27:30的格式
 * 因为在输出LocalDateTime对象时,会调用其重写的toString方法。
 */
public void formatter2() {
    String dateStr = "2020-11-12";
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDate formatterDate = LocalDate.parse(dateStr, dtf);
    System.out.println(formatterDate);
    //输出:2020-11-12
}

2.2.3 将时间日期对象转为格式化后的时间日期对象

/**
 * 将时间日期对象转为格式化后的时间日期对象
 */
public void formatter3() {
    //新的格式化API中,格式化后的结果都默认是String,有时我们也需要返回经过格式化的同类型对象
    LocalDateTime ldt1 = LocalDateTime.now();
    DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String temp = dtf1.format(ldt1);
    System.out.println(temp);

    LocalDateTime formatedDateTime = LocalDateTime.parse(temp, dtf1);
    System.out.println(formatedDateTime);
    
    /*输出:
        2022-05-21 16:53:02
        2022-05-21T16:23:39
    */
}

2.3 转换

2.3.1 localDate转date

/**
 * localDate 转 date
 * localDateTime 转 date
 *
 */
public void localDateToDate() {
    LocalDate now = LocalDate.now();
    Date from = Date.from(now.atStartOfDay(ZoneOffset.systemDefault()).toInstant());
    System.out.println(from);

    LocalDateTime localDateTime = LocalDateTime.now();
    Date date = Date.from(localDateTime.atZone(ZoneOffset.ofHours(8)).toInstant());
    System.out.println(date);

    /*输出:
        Sat May 21 00:00:00 CST 2022
        Sat May 21 16:25:38 CST 2022
    */
}

2.3.2 date转localDate

/**
 * date 转 localDate
 * date 转 localDateTime
 *
 */
public void dateToLocalDate() {
    Date date = new Date();
    
    LocalDate localDate = date.toInstant().atZone(ZoneOffset.systemDefault()).toLocalDate();
    System.out.println(localDate);
    
    LocalDateTime localDateTime = date.toInstant().atZone(ZoneOffset.systemDefault())
                .toLocalDateTime();
    System.out.println(localDateTime);

    /*输出:
        2022-05-21
        2022-05-21T16:26:42.636
    */
}

2.3.3 localDate转时间戳

/**
 * LocalDate 转 时间戳
 * LocalDateTime 转 时间戳
 */
public void localDateToInstant() {
    LocalDate localDate = LocalDate.now();
    long instant = localDate.atStartOfDay(ZoneOffset.systemDefault()).toInstant().toEpochMilli();
    System.out.println(instant);
    
    LocalDateTime now = LocalDateTime.now();
    long instant1 = now.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
    System.out.println(instant1);

    /*输出:
        1653062400000
        1653121639197
    */
}

2.3.4 时间戳转localDate

/**
 * 时间戳 转 LocalDate
 * 时间戳 转 LocalDateTime
 */
public void instantToLocalDate() {
    long time = new Date().getTime();
    LocalDateTime localDateTime = Instant.ofEpochMilli(time).atZone(ZoneOffset.systemDefault())
                .toLocalDateTime();
    System.out.println(localDateTime);
    
    LocalDate localDate = Instant.ofEpochMilli(time).atZone(ZoneOffset.systemDefault()).toLocalDate();
    System.out.println(localDate);

    /*输出:
        2022-05-21T16:27:55.876
        2022-05-21
    */
}

2.3.5 localDate转String

/**
 * localDate 转 String
 * LocalDateTime 转 String
 */
public void localDateToString() {
    
    //localDate转换成String
    LocalDate localDate = LocalDate.now();
    //按照yyyyMMdd样式进行更改
    String format1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);
    System.out.println(format1);

    //按照yyyy-MM-dd样式进行更改
    String format2 = localDate.format(DateTimeFormatter.ISO_DATE);
    System.out.println(format2);

    //自定义样式进行更改
    DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
    String format3 = localDate.format(pattern);
    System.out.println(format3);

    //LocalTime类型转换为String类型
    //按照xx:xx:xx.xx样式进行转换
    LocalTime localTime = LocalTime.now();
    String format4 = localTime.format(DateTimeFormatter.ISO_TIME);
    System.out.println(format4);

    //按照自定义样式进行转换
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss");
    String format5 = localTime.format(formatter);
    System.out.println(format5);

    //LocalDateTime类型转换为String类型
    LocalDateTime localDateTime = LocalDateTime.now();
    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
    String format6 = localDateTime.format(formatter2);
    System.out.println(format6);

    /*输出:
        20220521
        2022-05-21
        2022年05月21日
        16:40:36.817
        04:40:36
        2022-05-21 04:40:36
    */
}

2.4 时间工具类

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Java8日期时间工具类
 *
 * @date 2020/12/13
 */
public class LocalDateUtils {

    /**
     * 显示年月日时分秒,例如:2015-08-11 09:51:53
     */
    public static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     * 仅显示年月日,例如:2015-08-11
     */
    public static final String DATE_PATTERN = "yyyy-MM-dd";

    /**
     * 仅显示时分秒,例如:09:51:53
     */
    public static final String TIME_PATTERN = "HH:mm:ss";

    /**
     * 显示年月日时分秒(无符号),例如:20150811095153
     */
    public static final String UNSIGNED_DATETIME_PATTERN = "yyyyMMddHHmmss";

    /**
     * 仅显示年月日(无符号),例如:20150811
     */
    public static final String UNSIGNED_DATE_PATTERN = "yyyyMMdd";

    /**
     * 年
     */
    private static final String YEAR = "year";

    /**
     * 月
     */
    private static final String MONTH = "month";

    /**
     * 周
     */
    private static final String WEEK = "week";

    /**
     * 日
     */
    private static final String DAY = "day";

    /**
     * 时
     */
    private static final String HOUR = "hour";

    /**
     * 分
     */
    private static final String MINUTE = "minute";

    /**
     * 秒
     */
    private static final String SECOND = "second";

    /**
     * 获取当前日期和时间字符串
     *
     * @return String 日期时间字符串,例如:2015-08-11 09:51:53
     */
    public static String getLocalDateTime() {
        return format(LocalDateTime.now(), DATETIME_PATTERN);
    }

    /**
     * 获取当前日期字符串
     *
     * @return String 日期字符串,例如:2015-08-11
     */
    public static String getLocalDate() {
        return format(LocalDate.now(), DATE_PATTERN);
    }

    /**
     * 获取当前时间字符串
     *
     * @return String 时间字符串,例如: 09:51:53
     */
    public static String getLocalTime() {
        return format(LocalTime.now(), TIME_PATTERN);
    }

    /**
     * 获取当前星期字符串
     *
     * @return String 当前星期字符串,例如:星期二
     */
    public static String getDayOfWeek() {
        return format(LocalDate.now(), "E");
    }

    /**
     * 获取指定日期是星期几
     *
     * @param localDate 日期
     * @return String 星期几
     */
    public static String getDayOfWeek(LocalDate localDate) {
        return localDate.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.CHINA);
    }

    /**
     * 获取日期时间字符串
     *
     * @param temporal 需要转化的日期时间
     * @param pattern  时间格式
     * @return String 日期时间字符串,例如:2015-08-11 09:51:53
     */
    public static String format(TemporalAccessor temporal, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return dateTimeFormatter.format(temporal);
    }

    /**
     * 日期时间字符串转换为日期时间(java.time.LocalDateTime)
     *
     * @param localDateTime 日期时间字符串
     * @param pattern       日期时间格式 例如:DATETIME_PATTERN
     * @return LocalDateTime 日期时间
     */
    public static LocalDateTime parseLocalDateTime(String localDateTime, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(localDateTime, dateTimeFormatter);
    }

    /**
     * 日期字符串转换为日期(java.time.LocalDate)
     *
     * @param localDate 日期字符串
     * @param pattern   日期格式 例如:DATE_PATTERN
     * @return LocalDate 日期
     */
    public static LocalDate parseLocalDate(String localDate, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return LocalDate.parse(localDate, dateTimeFormatter);
    }

    /**
     * 获取指定日期时间加上指定数量日期时间单位之后的日期时间
     *
     * @param localDateTime 日期时间
     * @param num           数量
     * @param chronoUnit    日期时间单位
     *                      ChronoUnit.YEARS
     *                      ChronoUnit.MONTHS
     *                      ChronoUnit.WEEKS
     *                      ChronoUnit.DAYS
     * @return LocalDateTime 新的日期时间
     */
    public static LocalDateTime plus(LocalDateTime localDateTime, int num, ChronoUnit chronoUnit) {
        return localDateTime.plus(num, chronoUnit);
    }

    /**
     * 获取指定日期时间减去指定数量日期时间单位之后的日期时间
     *
     * @param localDateTime 日期时间
     * @param num           数量
     * @param chronoUnit    日期时间单位
     *                      ChronoUnit.YEARS
     *                      ChronoUnit.MONTHS
     *                      ChronoUnit.WEEKS
     *                      ChronoUnit.DAYS
     * @return LocalDateTime 新的日期时间
     */
    public static LocalDateTime minus(LocalDateTime localDateTime, int num, ChronoUnit chronoUnit) {
        return localDateTime.minus(num, chronoUnit);
    }

    /**
     * 根据ChronoUnit计算两个日期时间之间相隔日期时间
     *
     * @param start      开始日期时间
     * @param end        结束日期时间
     * @param chronoUnit 日期时间单位
     *                   ChronoUnit.YEARS
     *                   ChronoUnit.MONTHS
     *                   ChronoUnit.WEEKS
     *                   ChronoUnit.DAYS
     * @return long 相隔日期时间
     */
    public static long getChronoUnitBetween(LocalDateTime start, LocalDateTime end,
                                            ChronoUnit chronoUnit) {
        return Math.abs(start.until(end, chronoUnit));
    }

    /**
     * 根据ChronoUnit计算两个日期之间相隔年数或月数或天数
     *
     * @param start      开始日期
     * @param end        结束日期
     * @param chronoUnit 日期时间单位
     *                   ChronoUnit.YEARS
     *                   ChronoUnit.MONTHS
     *                   ChronoUnit.WEEKS
     *                   ChronoUnit.DAYS
     * @return long 相隔年数或月数或天数
     */
    public static long getChronoUnitBetween(LocalDate start, LocalDate end, ChronoUnit chronoUnit) {
        return Math.abs(start.until(end, chronoUnit));
    }

    /**
     * 获取本年第一天
     *
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfYear() {
        return getFirstDayOfYear(LocalDateTime.now());
    }

    /**
     * 获取本年最后一天
     *
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfYear() {
        return getLastDayOfYear(LocalDateTime.now());
    }

    /**
     * 获取指定日期当年第一天
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfYear(LocalDateTime localDateTime) {
        return getFirstDayOfYear(localDateTime, DATETIME_PATTERN);
    }

    /**
     * 获取指定日期当年最后一天
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfYear(LocalDateTime localDateTime) {
        return getLastDayOfYear(localDateTime, DATETIME_PATTERN);
    }

    /**
     * 获取指定日期当年第一天,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @param pattern       日期时间格式
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfYear(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.withDayOfYear(1).withHour(0).withMinute(0).withSecond(0), pattern);
    }

    /**
     * 获取指定日期当年最后一天,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @param pattern       日期时间格式
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfYear(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.with(TemporalAdjusters.lastDayOfYear())
                        .withHour(23).withMinute(59).withSecond(59),
                pattern);
    }

    /**
     * 获取本月第一天
     *
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfMonth() {
        return getFirstDayOfMonth(LocalDateTime.now());
    }

    /**
     * 获取本月最后一天
     *
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfMonth() {
        return getLastDayOfMonth(LocalDateTime.now());
    }

    /**
     * 获取指定日期当月第一天
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getFirstDayOfMonth(LocalDateTime localDateTime) {
        return getFirstDayOfMonth(localDateTime, DATETIME_PATTERN);
    }

    /**
     * 获取指定日期当月最后一天
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfMonth(LocalDateTime localDateTime) {
        return getLastDayOfMonth(localDateTime, DATETIME_PATTERN);
    }

    /**
     * 获取指定日期当月第一天,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfMonth(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0),
                pattern);
    }

    /**
     * 获取指定日期当月最后一天,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @param pattern       日期时间格式
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfMonth(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.with(TemporalAdjusters.lastDayOfMonth())
                        .withHour(23).withMinute(59).withSecond(59),
                pattern);
    }

    /**
     * 获取下月第一天
     *
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfNextMonth() {
        return getFirstDayOfNextMonth(LocalDateTime.now());
    }

    /**
     * 获取指定日期下月第一天
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getFirstDayOfNextMonth(LocalDateTime localDateTime) {
        return getFirstDayOfNextMonth(localDateTime, DATETIME_PATTERN);
    }

    /**
     * 获取指定日期下月第一天,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfNextMonth(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.with(TemporalAdjusters.firstDayOfNextMonth()),
                pattern);
    }

    /**
     * 获取下月最后一天
     *
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getLastDayOfNextMonth() {
        return getLastDayOfNextMonth(LocalDateTime.now());
    }

    /**
     * 获取指定日期下月最后一天
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfNextMonth(LocalDateTime localDateTime) {
        return getLastDayOfNextMonth(localDateTime, DATETIME_PATTERN);
    }

    /**
     * 获取指定日期下月最后一天,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getLastDayOfNextMonth(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.plus(1,ChronoUnit.MONTHS).with(TemporalAdjusters.lastDayOfMonth()),
                pattern);
    }

    /**
     * 获取本周第一天(周一)
     *
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfWeek() {
        return getFirstDayOfWeek(LocalDateTime.now());
    }

    /**
     * 获取本周最后一天(周日)
     *
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfWeek() {
        return getLastDayOfWeek(LocalDateTime.now());
    }

    /**
     * 获取指定日期当周第一天(周一)
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfWeek(LocalDateTime localDateTime) {
        return getFirstDayOfWeek(localDateTime, DATETIME_PATTERN);
    }

    /**
     * 获取指定日期当周最后一天(周日)
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfWeek(LocalDateTime localDateTime) {
        return getLastDayOfWeek(localDateTime, DATETIME_PATTERN);
    }

    /**
     * 获取指定日期当周第一天(周一)
     *
     * @param localDateTime 指定日期时间
     * @param pattern       日期时间格式
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfWeek(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.with(DayOfWeek.MONDAY)
                        .withHour(0).withMinute(0).withSecond(0),
                pattern);
    }

    /**
     * 获取指定日期当周最后一天(周日),带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @param pattern       日期时间格式
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfWeek(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.with(DayOfWeek.SUNDAY)
                        .withHour(23).withMinute(59).withSecond(59),
                pattern);
    }

    /**
     * 获取当前开始时间
     *
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getStartTimeOfDay() {
        return getStartTimeOfDay(LocalDateTime.now());
    }

    /**
     * 获取当前结束时间
     *
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getEndTimeOfDay() {
        return getEndTimeOfDay(LocalDateTime.now());
    }

    /**
     * 获取指定日期开始时间
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getStartTimeOfDay(LocalDateTime localDateTime) {
        return getStartTimeOfDay(localDateTime, DATETIME_PATTERN);
    }

    /**
     * 获取指定日期结束时间
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getEndTimeOfDay(LocalDateTime localDateTime) {
        return getEndTimeOfDay(localDateTime, DATETIME_PATTERN);
    }

    /**
     * 获取指定日期开始时间,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @param pattern       日期时间格式
     * @return String 格式:yyyy-MM-dd HH:mm:ss
     */
    public static String getStartTimeOfDay(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.withHour(0).withMinute(0).withSecond(0), pattern);
    }

    /**
     * 获取指定日期结束时间,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @param pattern       日期时间格式
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getEndTimeOfDay(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.withHour(23).withMinute(59).withSecond(59), pattern);
    }

    /**
     * 切割日期。按照周期切割成小段日期段
     *
     * @param startDate 开始日期(yyyy-MM-dd)
     * @param endDate   结束日期(yyyy-MM-dd)
     * @param period    周期(天,周,月,年)
     * @return 切割之后的日期集合
     * 例如:
     * <li>startDate="2019-02-28",endDate="2019-03-05",period="day"</li>
     * <li>结果为:[2019-02-28, 2019-03-01, 2019-03-02, 2019-03-03, 2019-03-04, 2019-03-05]</li>
     * <br>
     * <li>startDate="2019-02-28",endDate="2019-03-20",period="week"</li>
     * <li>结果为:[2019-02-28,2019-03-06, 2019-03-07,2019-03-13, 2019-03-14,2019-03-20]</li>
     * <br>
     * <li>startDate="2019-02-28",endDate="2019-04-30",period="month"</li>
     * <li>结果为:[2019-02-28,2019-02-28, 2019-03-01,2019-03-31, 2019-04-01,2019-04-30]</li>
     * <br>
     * <li>startDate="2019-02-28",endDate="2020-05-25",period="year"</li>
     * <li>结果为:[2019-02-28,2019-12-31, 2020-01-01,2020-05-25]</li>
     * <br>
     */
    public static List<String> listDateStrs(String startDate, String endDate, String period) {
        List<String> result = new ArrayList<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_PATTERN);
        LocalDate end = LocalDate.parse(endDate, dateTimeFormatter);
        LocalDate start = LocalDate.parse(startDate, dateTimeFormatter);
        LocalDate tmp = start;
        switch (period) {
            case DAY:
                while (start.isBefore(end) || start.isEqual(end)) {
                    result.add(start.toString());
                    start = start.plusDays(1);
                }
                break;
            case WEEK:
                while (tmp.isBefore(end) || tmp.isEqual(end)) {
                    if (tmp.plusDays(6).isAfter(end)) {
                        result.add(tmp + "," + end);
                    } else {
                        result.add(tmp + "," + tmp.plusDays(6));
                    }
                    tmp = tmp.plusDays(7);
                }
                break;
            case MONTH:
                while (tmp.isBefore(end) || tmp.isEqual(end)) {
                    LocalDate lastDayOfMonth = tmp.with(TemporalAdjusters.lastDayOfMonth());
                    if (lastDayOfMonth.isAfter(end)) {
                        result.add(tmp + "," + end);
                    } else {
                        result.add(tmp + "," + lastDayOfMonth);
                    }
                    tmp = lastDayOfMonth.plusDays(1);
                }
                break;
            case YEAR:
                while (tmp.isBefore(end) || tmp.isEqual(end)) {
                    LocalDate lastDayOfYear = tmp.with(TemporalAdjusters.lastDayOfYear());
                    if (lastDayOfYear.isAfter(end)) {
                        result.add(tmp + "," + end);
                    } else {
                        result.add(tmp + "," + lastDayOfYear);
                    }
                    tmp = lastDayOfYear.plusDays(1);
                }
                break;
            default:
                break;
        }
        return result;
    }

    /**
     * 日期转为LocalDateTime
     *
     * @param date 日期
     * @return LocalDateTime
     */
    public static LocalDateTime dateToLocalDateTime(final Date date) {
        if (null == date) {
            return null;
        }
        final Instant instant = date.toInstant();
        final ZoneId zoneId = ZoneId.systemDefault();
        final LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        return localDateTime;
    }

    /**
     * 日期转为LocalDate
     *
     * @param date 日期
     * @return LocalDateTime
     */
    public static LocalDate dateToLocalDate(final Date date) {
        if (null == date) {
            return null;
        }
        final Instant instant = date.toInstant();
        final ZoneId zoneId = ZoneId.systemDefault();
        final LocalDate localDate = instant.atZone(zoneId).toLocalDate();
        return localDate;
    }

    /**
     * LocalDateTime转为日期
     *
     * @param localDateTime LocalDateTime
     * @return 日期
     */
    public static Date localDateTimeToDate(final LocalDateTime localDateTime) {
        if (null == localDateTime) {
            return null;
        }
        final ZoneId zoneId = ZoneId.systemDefault();
        final ZonedDateTime zdt = localDateTime.atZone(zoneId);
        final Date date = Date.from(zdt.toInstant());
        return date;
    }

    /**
     * LocalDate转为日期
     *
     * @param localDate
     * @return
     */
    public static Date localDateToDate(final LocalDate localDate) {
        if (null == localDate) {
            return null;
        }
        final ZoneId zoneId = ZoneId.systemDefault();
        final ZonedDateTime zdt = localDate.atStartOfDay().atZone(zoneId);
        final Date date = Date.from(zdt.toInstant());
        return date;
    }

    public static void main(String[] args) {
        System.out.println(getLocalDateTime());
        System.out.println(getLocalDate());
        System.out.println(getLocalTime());
        System.out.println(getDayOfWeek());
        System.out.println(getDayOfWeek(LocalDate.now()));

        System.out.println("1========");
        System.out.println(format(LocalDate.now(), UNSIGNED_DATE_PATTERN));

        System.out.println("2========");
        System.out.println(parseLocalDateTime("2020-12-13 11:14:12", DATETIME_PATTERN));
        System.out.println(parseLocalDate("2020-12-13", DATE_PATTERN));

        System.out.println("3========");
        System.out.println(plus(LocalDateTime.now(), 3, ChronoUnit.HOURS));
        System.out.println(minus(LocalDateTime.now(), 4, ChronoUnit.DAYS));

        System.out.println("4========");
        System.out.println(getChronoUnitBetween(LocalDateTime.now(),
                parseLocalDateTime("2022-12-12 12:03:12", DATETIME_PATTERN),
                ChronoUnit.MINUTES));
        System.out.println(getChronoUnitBetween(LocalDateTime.now(),
                parseLocalDateTime("2022-07-29 12:03:12", DATETIME_PATTERN),
                ChronoUnit.DAYS));
        System.out.println(getChronoUnitBetween(LocalDate.now(),
                parseLocalDate("2022-12-12", DATE_PATTERN),
                ChronoUnit.WEEKS));

        System.out.println("5========");
        System.out.println(getFirstDayOfYear());
        System.out.println(getFirstDayOfYear(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN)));
        System.out.println(getFirstDayOfYear(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));

        System.out.println(getLastDayOfYear());
        System.out.println(getLastDayOfYear(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN)));
        System.out.println(getLastDayOfYear(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));

        System.out.println("6========");
        System.out.println(getFirstDayOfMonth());
        System.out.println(getFirstDayOfMonth(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN)));
        System.out.println(getFirstDayOfMonth(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));

        System.out.println(getLastDayOfMonth());
        System.out.println(getLastDayOfMonth(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN)));
        System.out.println(getLastDayOfMonth(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));

        System.out.println("7========");
        System.out.println(getFirstDayOfWeek());
        System.out.println(getFirstDayOfWeek(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN)));
        System.out.println(getFirstDayOfWeek(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));

        System.out.println(getLastDayOfWeek());
        System.out.println(getLastDayOfWeek(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN)));
        System.out.println(getLastDayOfWeek(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));

        System.out.println("8========");
        System.out.println(getStartTimeOfDay());
        System.out.println(getStartTimeOfDay(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN)));
        System.out.println(getStartTimeOfDay(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));

        System.out.println(getEndTimeOfDay());
        System.out.println(getEndTimeOfDay(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN)));
        System.out.println(getEndTimeOfDay(parseLocalDateTime("2021-12-12 12:03:12",
                DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));

        System.out.println("9========");
        List<String> dateStrs = listDateStrs("2019-01-30", "2020-12-13", YEAR);
        for (String dateStr : dateStrs) {
            System.out.println(dateStr);
        }

        System.out.println("10========");
        List<String> dateStrs1 = listDateStrs("2019-01-30", "2020-12-13", MONTH);
        for (String dateStr : dateStrs1) {
            System.out.println(dateStr);
        }

        System.out.println("11========");
        List<String> dateStrs2 = listDateStrs("2020-12-01", "2020-12-13", DAY);
        for (String dateStr : dateStrs2) {
            System.out.println(dateStr);
        }

        LocalDateTime localDateTime = LocalDateTime.now();
        DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
        String displayName = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.CHINA);
        //本周中星期几
        int value = dayOfWeek.getValue();
        System.out.println(dayOfWeek + displayName + value);

        LocalDateTime minTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime maxTime = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        ZoneId zone = ZoneId.systemDefault();
        Date[] dayArray2 = {Date.from(minTime.atZone(zone).toInstant()),
                                Date.from(maxTime.atZone(zone).toInstant())};
        for (Date date : dayArray2) {
            System.out.println(date);
        }
        System.out.println(getFirstDayOfNextMonth());
        System.out.println(getLastDayOfNextMonth());

    }
}

参考文章

posted @ 2022-05-23 20:14  夏尔_717  阅读(670)  评论(0编辑  收藏  举报