Java 8 LocalDateTime日期的介绍与使用【附DateUtils日期处理工具完整代码】

本文转载,原文地址: Java 8 LocalDateTime日期的介绍与使用【附DateUtils日期处理工具完整代码】    

Java 8 LocalDateTime日期的介绍与使用【附DateUtils日期处理工具完整代码】

About me


一个爱学习、爱分享、爱交流的程序员Boy;

欢迎关注个人微信公众号【Java烂笔头】,微信小程序【Java烂笔头】,一起交流、共同进步;

文章中源码获取:
                                  

 

前言
最近开发项目遇到很多日期处理相关的问题,比如本周的结束时间、上个月的开始时间、本季度的开始时间、指定日期的时间间隔……等等

开始还在用Calendar……那叫一个麻烦

后来发现LocalDateTime!真香!

简介
日期工具在Java开发过程中还是很常用的,尤其是在统计计算过程中,掌握好日期计算会大大提升开发效率!

Java 8 新特性之一:加强对时间和日期的处理,明确了日期时间概念;

例如:瞬时(instant)、时长(duration)、日期、时间、时区和周期。同时继承了Joda 库按人类语言和计算机各自解析的时间处理方式。不同于老版本,新API基于ISO标准日历系统,java.time包下的所有类都是不可变类型而且线程安全。

新增的关键日期类主要有五种:
java.time.Instant->瞬时时间

默认格式:yyyy-MM-ddTHH:mm:ss.SSSSSSSSSZ,例如:2022-10-15T13:21:48.602Z

/**
 *最小支持瞬时时间
 * The minimum supported {@code Instant}, '-1000000000-01-01T00:00Z'.
 * This could be used by an application as a "far past" instant.
 */
public static final Instant MIN = Instant.ofEpochSecond(MIN_SECOND, 0);
/**
 *最大支持瞬时时间
 * The maximum supported {@code Instant}, '1000000000-12-31T23:59:59.999999999Z'.
 * This could be used by an application as a "far future" instant.
 */
public static final Instant MAX = Instant.ofEpochSecond(MAX_SECOND, 999_999_999);

java.time.LocalDate ->只对年月日做出处理

默认格式:yyyy-MM-dd, 例如:2022-10-15

/**
 * 最小支持日期
 * The minimum supported {@code LocalDate}, '-999999999-01-01'.
 * This could be used by an application as a "far past" date.
 */
public static final LocalDate MIN = LocalDate.of(Year.MIN_VALUE, 1, 1);
/**
 * 最大支持日期
 * The maximum supported {@code LocalDate}, '+999999999-12-31'.
 * This could be used by an application as a "far future" date.
 */
public static final LocalDate MAX = LocalDate.of(Year.MAX_VALUE, 12, 31);

java.time.LocalTime ->只对时分秒纳秒做出处理

默认格式:HH:mm:ss.SSSSSSSSS 例如:21:30:39.412

/**
 * 最小支持时间
 * The minimum supported {@code LocalTime}, '00:00'.
 * This is the time of midnight at the start of the day.
 */
public static final LocalTime MIN;

/**
 * 最大支持时间
 * The maximum supported {@code LocalTime}, '23:59:59.999999999'.
 * This is the time just before midnight at the end of the day.
 */
public static final LocalTime MAX;

java.time.LocalDateTime ->同时可以处理年月日和时分秒

默认格式:yyyy-MM-ddTHH:mm:ss.SSSSSSSSS 例如:2022-10-15T21:30:39.413

/**
 * 最小支持日期时间
 * The minimum supported {@code LocalDateTime}, '-999999999-01-01T00:00:00'.
 * This is the local date-time of midnight at the start of the minimum date.
 */
public static final LocalDateTime MIN = LocalDateTime.of(LocalDate.MIN, LocalTime.MIN);


/**
 * 最大支持日期时间
 * The maximum supported {@code LocalDateTime}, '+999999999-12-31T23:59:59.999999999'.
 * This is the local date-time just before midnight at the end of the maximum date.
 */
public static final LocalDateTime MAX = LocalDateTime.of(LocalDate.MAX, LocalTime.MAX);


java.time.ZonedDateTime:最完整的日期-时间-时区-相对UTC或格林威治的时差
默认格式:yyyy-MM-ddTHH:mm:ss.SSSSSSSSS+08:00[Asia/Shanghai] 例如:2022-10-15T21:30:39.414+08:00[Asia/Shanghai]

一、创建LocalDateTime


方法说明:

/**
 * static LocalDateTime ofInstant(Instant instant, ZoneId zone)    通过Instant实例与时区创建时间
 * static LocalDateTime now()  获取默认时区的当前日期时间,默认格式yyyy-MM-ddTHH:mm:ss.SSSSSSSSS
 * static LocalDateTime now(ZoneId zone)   从指定时区获取日期时间
 * static LocalDateTime now(Clock clock)   从指定闹钟获取日期时间
 * static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second)    根据年月日时分秒创建日期时间
 * static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)  根据年月日时分秒纳秒创建日期时间
 * static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second)  根据年月日时分秒创建日期时间
 * static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)    根据年月日时分秒纳秒创建日期时间
 * static LocalDateTime of(LocalDate date, LocalTime time) 根据LocalDate与LocalTime创建时间
 * static LocalDateTime ofEpochSecond(long epochSecond, int nanoOfSecond, ZoneOffset offset)   通过毫秒数、纳秒数及时区创建时间epochSecond:从1970-01-01T00:00:00到指定时间的秒数
 */

使用示例:

 		System.out.println("创建Instant实例时间:" + LocalDateTime.ofInstant(Instant.now(), ZoneId.of("UTC")));
        System.out.println("当前默认日期时间:" + LocalDateTime.now());
        System.out.println("当前指定时区时间:" + LocalDateTime.now(ZoneId.systemDefault()));
        System.out.println("当前指定闹钟时间:" + LocalDateTime.now(Clock.systemUTC()));
        System.out.println("指定年月日时分秒时间:" + LocalDateTime.of(2022, Month.OCTOBER, 15, 9, 51, 15));
        System.out.println("指定时分秒纳秒时间:" + LocalDateTime.of(2022, Month.OCTOBER, 15, 9, 51, 15, 1));
        System.out.println("指定时分秒时间:" + LocalDateTime.of(2022, 10, 15, 9, 51, 15));
        System.out.println("指定时分秒纳秒时间:" + LocalDateTime.of(2022, 12, 15, 9, 51, 15, 1));
        System.out.println("localDate、LocalTime时间:" + LocalDateTime.of(LocalDate.now(), LocalTime.now()));
        System.out.println("通过秒、毫秒创建时间:" + LocalDateTime.ofEpochSecond(Instant.now().getEpochSecond(), 222, ZoneOffset.UTC));

测试结果:
创建Instant实例时间:2022-10-15T13:56:22.953
当前默认日期时间:2022-10-15T21:56:22.953
当前指定时区时间:2022-10-15T21:56:22.953
当前指定闹钟时间:2022-10-15T13:56:22.954
指定年月日时分秒时间:2022-10-15T09:51:15
指定时分秒纳秒时间:2022-10-15T09:51:15.000000001
指定时分秒时间:2022-10-15T09:51:15
指定时分秒纳秒时间:2022-12-15T09:51:15.000000001
localDate、LocalTime时间:2022-10-15T21:56:22.955
通过秒、毫秒创建时间:2022-10-15T13:56:22.000000222

二、获取年月日时分秒纳秒


方法说明:

/**
 * int getYear()   获取年份
 * Month getMonth()    使用月枚举类型获取月份
 * int getMonthValue() 返回数字月份 1-12月
 * int getDayOfMonth() 获取日期在该月是第几天
 * DayOfWeek getDayOfWeek()    获取日期是星期几
 * int getDayOfYear()  获取日期在该年是第几天
 * int getHour()   获取小时, 返回0到23
 * int getMinute() 获取分钟, 返回0到59
 * int getSecond() 获取秒,返回0到59
 * int getNano()   获取纳秒,返回0到999,999,999
 */

使用示例:

		//获取当前时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前默认时间:" + now);
        //获取年份
        System.out.println("年:" + now.getYear());
        //获取月份
        System.out.println("月:" + now.getMonth().getValue());
        //获取当前日期是当月的第几天
        System.out.println("日:" + now.getDayOfMonth());
        //获取当前日期是星期几
        System.out.println("星期几:" + now.getDayOfWeek());
        //获取当前日期是当年的第几天
        System.out.println("日:" + now.getDayOfYear());
        //获取小时、分钟、秒、纳秒
        System.out.println("当前时间:" + now.getHour() + "小时," + now.getMinute() + "分钟," + now.getSecond() + "秒," + now.getNano() + "纳秒");
        //通用获取日期时间方法
        System.out.println("当前时间:" + now.get(ChronoField.HOUR_OF_DAY) + "小时," + now.get(ChronoField.MINUTE_OF_HOUR) + "分钟," + now.get(ChronoField.SECOND_OF_MINUTE) + "秒");




测试结果:
当前默认时间:2022-10-15T22:02:47.159
年:2022
月:10
日:15
星期几:SATURDAY
日:288
当前时间:22小时,2分钟,47秒,159000000纳秒
当前时间:22小时,2分钟,47秒

三、LocalDateTime日期比较


方法说明:
 

/**
 * boolean isBefore(ChronoLocalDateTime<?> other)  检查日期是否在指定日期之前
 * boolean isAfter(ChronoLocalDateTime<?> other)   检查日期是否在指定日期之后
 * boolean isEqual(ChronoLocalDateTime<?> other)   比较日期是否相同
 * int compareTo(ChronoLocalDateTime<?> other) 日期比较localDateTimeA.compareTo(localDateTimeB),若相等返回0;若A>B,返回1 ;若A<B返回-1
 */

使用示例:

LocalDateTime before = LocalDateTime.parse("2022-10-13T08:26:32.000000000");
LocalDateTime after  = LocalDateTime.parse("2022-10-15T20:27:36.000000000");
System.out.println(before.isBefore(after));//true
System.out.println(before.isAfter(after));//false
System.out.println(before.isEqual(before)); //true

System.out.println(before.compareTo(after));//-1
System.out.println(after.compareTo(before));//1
System.out.println(after.compareTo(after));//0

测试结果:

true
false
true
-2
2
0

四、日期计算

4.1、加/减年、月、周、日、时、分、秒

方法说明:

/**
 * LocalDateTime plus(TemporalAmount amountToAdd)  通过TemporalAmount对象增加指定日期时间,TemporalAmount的实现一般是Period,Duration对象
 * LocalDateTime plus(long amountToAdd, TemporalUnit unit) 通用方法,可以通过unit参数控制增加天、周、月、年
 * LocalDateTime plusDays(long daysToAdd)  返回增加了*天的LocalDateTime 副本
 * LocalDateTime plusWeeks(long weeksToAdd)    返回增加了*周的LocalDateTime 副本
 * LocalDateTime plusMonths(long monthsToAdd)  返回增加了*月的LocalDateTime 副本
 * LocalDateTime plusYears(long yearsToAdd)    返回增加了*年的LocalDateTime 副本
 * LocalDateTime plusHours(long hours) 返回增加了*小时的LocalDateTime 副本
 * LocalDateTime plusMinutes(long minutes) 返回增加了*分钟的LocalDateTime 副本
 * LocalDateTime plusSeconds(long seconds) 返回增加了*秒的LocalDateTime 副本
 * LocalDateTime plusNanos(long nanos) 返回增加了*纳秒的LocalDateTime 副本
 * LocalDateTime minus(TemporalAmount amountToAdd) 通过TemporalAmount对象减少指定日期时间,TemporalAmount的实现一般是Period,Duration对象
 * LocalDateTime minus(long amountToAdd, TemporalUnit unit)    通用方法,可以通过unit参数控制减少天、周、月、年
 * LocalDateTime minusDays(long daysToSubtract)    返回减少了*天的LocalDateTime 副本
 * LocalDateTime minusWeeks(long weeksToSubtract)  返回减少了*周的LocalDateTime 副本
 * LocalDateTime minusMonths(long monthsToSubtract)    返回减少了*月的LocalDateTime 副本
 * LocalDateTime minusYears(long yearsToSubtract)  返回减少了*年的LocalDateTime 副本
 * LocalDateTime minusHours(long hours)    返回减少了*小时的LocalDateTime 副本
 * LocalDateTime minusMinutes(long minutes)    返回减少了*分钟的LocalDateTime 副本
 * LocalDateTime minusSeconds(long seconds)    返回减少了*秒的LocalDateTime 副本
 * LocalDateTime minusNanos(long nanos)    返回减少了*纳秒的LocalDateTime 副本
 */

使用示例:

LocalDateTime localDateTime = LocalDateTime.parse("2022-10-15T10:14:23");
System.out.println("增加1年:" + localDateTime.plusYears(1));
System.out.println("增加1月:" + localDateTime.plusMonths(1));
System.out.println("增加1天:" + localDateTime.plusDays(1));

System.out.println("减少1小时:" + localDateTime.minusHours(1));
System.out.println("减少1分钟:" + localDateTime.minusMinutes(1));
System.out.println("减少1秒:" + localDateTime.minusSeconds(1));

System.out.println("增加2个月:" + localDateTime.plus(Period.ofMonths(2)));
System.out.println("增加2天:" + localDateTime.plus(Duration.ofDays(2)));
System.out.println("增加1纳秒:" + localDateTime.plus(1, ChronoUnit.NANOS));
System.out.println("减少1分钟:" + localDateTime.minus(1, ChronoUnit.MINUTES));

测试结果:
增加1年:2023-10-15T10:14:23
增加1月:2022-11-15T10:14:23
增加1天:2022-10-16T10:14:23
减少1小时:2022-10-15T09:14:23
减少1分钟:2022-10-15T10:13:23
减少1秒:2022-10-15T10:14:22
增加2个月:2022-12-15T10:14:23
增加2天:2022-10-17T10:14:23
增加1纳秒:2022-10-15T10:14:23.000000001
减少1分钟:2022-10-15T10:13:23

4.2、计算两个日期时间的间隔


方法一:通过Duration计算两个LocalTime相差的时间

使用示例:
 

 	LocalDateTime start = LocalDateTime.parse("2021-07-07T08:30:01");
    LocalDateTime end   = LocalDateTime.parse("2022-10-15T22:25:23");
    //between的用法是end-start的时间,若start的时间大于end的时间,则所有的值是负的
    Duration duration = Duration.between(start, end);
    System.out.printf("两个时间相差:%d天,相差:%d小时,相差:%d分钟%n", duration.toDays(), duration.toHours(), duration.toMinutes());
}

测试结果:

两个时间相差:1天,相差86700秒,相差:24小时,相差:1445分钟

方法二:ChronoUnit也可以计算两个单元之间的差值。

使用示例:

LocalDateTime start = LocalDateTime.parse("2021-07-07T08:30:01");
LocalDateTime end   = LocalDateTime.parse("2022-10-15T22:25:23");
long day = ChronoUnit.DAYS.between(start, end);
long hour = ChronoUnit.HOURS.between(start, end);
long minute = ChronoUnit.MINUTES.between(start, end);
long seconds = ChronoUnit.SECONDS.between(start, end);

测试结果:

两个时间相差:465天,相差40226122秒,相差:11173小时,相差:670435分钟

方法三:通过LocalDateTime类的toEpochSecond()方法,返回时间对应的秒数,然后计算出两个时间相差的间隔

使用示例:

LocalDateTime start = LocalDateTime.parse("2021-07-07T08:30:01");
LocalDateTime end   = LocalDateTime.parse("2022-10-15T22:25:23");
System.out.println("两个时间相差:" + (end.toEpochSecond(ZoneOffset.UTC) - start.toEpochSecond(ZoneOffset.UTC)) + "秒");

测试结果:

两个时间相差:40226122秒

五、时间格式化

方法说明:

/**
 * static LocalDateTime parse(CharSequence text)   从文本字符串获取LocalDateTime实例,text格式一般是2007-12-03T10:15:30
 * static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter)  使用特定格式化形式从文本字符串获取LocalDateTime实例,text的格式一般与formatter格式一致
 * String format(DateTimeFormatter formatter)  将LocalTime转为特定格式的字符串
 */

使用示例:

LocalDateTime time = LocalDateTime.parse("2022-10-15T10:46:01");
System.out.println(time); //2021-12-06T11:01:01

//若使用parse(CharSequence text, DateTimeFormatter formatter),text格式需与formatter格式一致,否则可能会报错
time = LocalDateTime.parse("2022-10-15 10:46:01", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(time);//2021-12-06T11:01:01

String time1 = time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss"));
System.out.println(time1); //2021-12-06 11-01-01

测试结果:
2022-10-15T10:46:01
2022-10-15T10:46:01
2022-10-15 10-46-01

注意:
parse(CharSequence text, DateTimeFormatter formatter)与format(DateTimeFormatter formatter)两个方法表现不一样,parse后输出格式为yyyy-MM-ddTHH:mm:ss.SSSSSSSSS,format后输出格式为formatter样式。

六、LocalDateTime日期修改


方法说明:
 

/**
 * LocalDateTime with(TemporalAdjuster adjuster)   使用传递的TemporalAdjuster时间调节器作为参数来调整此日期时间,并在调整后返回调整后的时间的副本
 * LocalDateTime with(TemporalField field, long newValue)  用于将LocalTime的指定字段设置为新值并返回新的时间的副本。此方法可用于更改任何受支持的字段,例如时、分、秒…。如果由于不支持该字段或其他原因而无法设置新值,则会引发异常。
 * LocalDateTime withYear(int year)    修改LocalTime变量的年
 * LocalDateTime withMonth(int month)  修改LocalTime变量的月份
 * LocalDateTime withDayOfMonth(int dayOfMonth)    修改LocalTime变量的日
 * LocalDateTime withHour(int hour)    修改LocalTime变量的小时,hour:从0到23
 * LocalDateTime withMinute(int minute)    修改LocalDateTime变量的分钟,minute:从0到59
 * LocalDateTime withSecond(int second)    修改LocalDateTime变量的秒,second:从0到59
 * LocalDateTime withNano(int nanoOfSecond)    修改LocalDateTime变量的纳秒,nanoOfSecond:从0到999,999,999
 */

使用示例:

     	LocalDateTime localDateTimeUpdate = LocalDateTime.parse("2022-10-12T11:36:00");
        //修改LocalDateTime变量的年
        System.out.println(localDateTimeUpdate.withYear(2023));
        //修改LocalDateTime变量的月
        System.out.println(localDateTimeUpdate.withMonth(8));

        //修改LocalDateTime变量的小时
        System.out.println(localDateTimeUpdate.withHour(8));
        //修改LocalDateTime变量的分钟
        System.out.println(localDateTimeUpdate.withMinute(20));
        //修改LocalDateTime变量的秒
        System.out.println(localDateTimeUpdate.withSecond(1));
        //修改LocalDateTime变量的纳秒
        System.out.println(localDateTimeUpdate.withNano(1));

        //通用方法,修改LocalDateTime变量的日
        System.out.println(localDateTimeUpdate.with(ChronoField.DAY_OF_MONTH, 12));

测试结果:
2023-10-12T11:36
2022-08-12T11:36
2022-10-12T08:36
2022-10-12T11:20
2022-10-12T11:36:01
2022-10-12T11:36:00.000000001
2022-10-12T11:36

七、日期转换


7.1、LocalDateTime、LocalDate、LocalTime、Instant转换
 

使用示例:
 

LocalDateTime local = LocalDateTime.parse("2022-10-12T11:36:00");
//1. LocalDateTime转LocalDate
LocalDate localDate = local.toLocalDate();
System.out.println("日期:" + localDate);

//2. LocalDateTime转LocalTime
LocalTime localTime = local.toLocalTime();
System.out.println("时间:" + localTime);
//3. LocalDate转LocalDateTime
//3.1 LocalDateTime atTime(LocalTime time)
localDateTime = localDate.atTime(localTime);
System.out.println(localDateTime);
//3.2 LocalDateTime atTime(int hour, int minute, int second)
localDateTime = localDate.atTime(10, 11, 11);
System.out.println(localDateTime);
//3.3 LocalDateTime atTime(int hour, int minute, int second, int nanoOfSecond)
localDateTime = localDate.atTime(10, 11, 11, 1);
System.out.println(localDateTime);
//3.4 获得一天的开始
LocalDateTime beginningOfDay = LocalDate.parse("2020-03-16").atStartOfDay();
System.out.println(localDateTime);
//4. LocalTime转LocalDateTime
//4.1 LocalDateTime atDate(LocalDate date)
localDateTime = localTime.atDate(localDate);
System.out.println(localDateTime);

测试结果:


日期:2022-10-12
时间:11:36
2022-10-12T11:36
2022-10-12T10:11:11
2022-10-12T10:11:11.000000001
2022-10-12T10:11:11.000000001
2022-10-12T11:36

7.2、LocalDateTime转为Instant、获取时间戳

使用示例:
 

LocalDateTime localDateTimeChange = LocalDateTime.parse("2022-10-12T11:36:00");

//1.LocalDateTime转Instant
Instant instant = localDateTimeChange.toInstant(ZoneOffset.UTC);
System.out.println(instant);

//2. 获取距离1970-01-01T00:00:00Z的秒值
System.out.println(instant.getEpochSecond());

//3. Instant获取时间戳  获取距离1970-01-01T00:00:00Z的毫秒值  与System.currentTimeMillis()一样,返回毫秒数
System.out.println(instant.toEpochMilli());

测试结果:

2022-10-12T11:36:00Z
1665574560
1665574560000

7.3、LocalTime、LocalDateTime与Date转换

使用示例:

//1. Date转LocalDateTime  static LocalDateTime ofInstant(Instant instant, ZoneId zone)
LocalDateTime localDateTimeDate = LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault());
System.out.println(localDateTimeDate);

//2. Date转LocalTime    static LocalTime ofInstant(Instant instant, ZoneId zone)
LocalTime localTimeDate = localDateTimeDate.toLocalTime();
System.out.println(localTimeDate);

//3. LocalDateTime/LocalTime转Date  static Date from(Instant instant)
Date date = Date.from(localDateTimeDate.toInstant(ZoneId.systemDefault().getRules().getOffset(localDateTime)));
System.out.println(date);

//3.1 LocalDateTime/LocalTime转Date   Date(long date) date:毫秒值
date = new Date(localDateTimeDate.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
System.out.println(date);

测试结果:

2022-10-15T23:58:13.924
23:58:13.924
Sat Oct 15 23:58:13 CST 2022
Sat Oct 15 23:58:13 CST 2022

八、日期常用工具类

package com.javanoteany.date.util;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前LocalTime型 时间
     *
     * @return LocalTime 当前时间
     */
    public static LocalTime getNowTime() {
        return LocalTime.now();
    }

    /**
     * 获取当前LocalDate型日期
     * yyyy-MM-dd
     * @return LocalDate 当前日期
     */
    public static LocalDate getNowDate() {
        return LocalDate.now();
    }

    /**
     * 获取当前LocalDateTime型日期时间
     *
     * @return LocalDateTime 当前日期时间
     */
    public static LocalDateTime getNowDateTime() {
        return LocalDateTime.now();
    }

    /**
     * 获取指定日期的毫秒/日期转换为long类型时间戳
     *
     * @param localDateTime 输入日期
     * @return 毫秒 13位时间戳
     */
    public static Long getMillis(LocalDateTime localDateTime) {
        return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }


    /**
     * 获取指定日期的指定格式
     * @param localDateTime 指定日期
     * @param pattern 格式
     * @return String型日期
     */
    public static String formatTime(LocalDateTime localDateTime,String pattern) {
        return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
    }

    /**
     * 指定日期转换为String类型时间
     *
     * @param localDateTime 输入日期
     * @param pattern 输出日期的时间格式
     * @return String
     */
    public static String localDateTimeToString(LocalDateTime localDateTime, String pattern) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        return localDateTime.format(formatter);
    }

    /**
     * String类型时间转换为localDateTime日期
     *
     * @param stringTime 输入日期
     * @param pattern 输入日期的时间格式
     * @return String
     */
    public static LocalDateTime stringToLocalDateTime(String stringTime, String pattern) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(stringTime, formatter);
    }

    /**
     * String类型时间转换为localDateTime日期
     *
     * @param stringTime 输入日期
     * @param pattern 输入日期的时间格式
     * @return String
     */
    public static LocalDate stringToLocalDate(String stringTime, String pattern) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        return LocalDate.parse(stringTime, formatter);
    }

    /**
     * String类型时间转换为localDateTime日期
     *
     * @param stringTime 输入日期
     * @param pattern 输入日期的时间格式
     * @return String
     */
    public static LocalTime stringToLocalTime(String stringTime, String pattern) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        return LocalTime.parse(stringTime, formatter);
    }

    /**
     * Date转换为LocalDateTime
     * @param date 输入Date日期
     * @return LocalDateTime日期
     */
    public static LocalDateTime dateToLocalDateTime(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    /**
     * LocalDateTime转换为Date
     * @param localDateTime 输入LocalDateTime日期
     * @return 输出Date日期
     */
    public static Date localDateTimeToDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 获取两个日期的差  field参数为ChronoUnit.
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param field  单位(年月日时分秒) ChronoUnit.HOURS  ChronoUnit.DAYS 枚举
     * @return
     */
    public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
        Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));

        if (field == ChronoUnit.YEARS) return period.getYears();
        if (field == ChronoUnit.MONTHS) return period.getYears() * 12 + period.getMonths();
        return field.between(startTime, endTime);
    }

    /**
     * 日 开始时间、结束时间
     *
     * @param localDateTime 输入日期
     * @return todayTime
     */
    public static Map dayTime(LocalDateTime localDateTime) {
        Map todayTime = new HashMap<String, LocalDateTime>();
        todayTime.put("beginTime", localDateTime.with(LocalTime.MIN));
        todayTime.put("endTime", localDateTime.with(LocalTime.MAX));
        return todayTime;
    }

    /**
     * 周 开始时间、结束时间
     *
     * @param localDateTime 输入日期
     * @return weekTime
     */
    public static Map weekTime(LocalDateTime localDateTime) {
        Map weekTime = new HashMap<String, LocalDateTime>();
        int dayOfWeek = localDateTime.getDayOfWeek().getValue();
        LocalDateTime weekStart = localDateTime.minusDays(dayOfWeek - 1).with(LocalTime.MIN);
        LocalDateTime weekEnd = localDateTime.plusDays(7 - dayOfWeek).with(LocalTime.MAX);
        weekTime.put("beginTime", weekStart);
        weekTime.put("endTime", weekEnd);
        return weekTime;
    }

    /**
     * 月 开始时间、结束时间
     *
     * @param localDateTime 输入日期
     * @return monthTime
     */
    public static Map monthTime(LocalDateTime localDateTime) {
        Map monthTime = new HashMap<String, LocalDateTime>();
        LocalDateTime monthStart = localDateTime.with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
        LocalDateTime monthEnd = localDateTime.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);
        monthTime.put("beginTime", monthStart);
        monthTime.put("endTime", monthEnd);
        return monthTime;
    }

    /**
     * 季 开始时间、结束时间
     *
     * @param localDateTime 输入日期
     * @return seasonTime
     */
    public static Map seasonTime(LocalDateTime localDateTime) {
        Map seasonTime = new HashMap<String, LocalDateTime>();
        LocalDate seasonStartDate = LocalDate.of(localDateTime.getYear(), localDateTime.getMonth().firstMonthOfQuarter(), 1);
        LocalDate seasonEndDate = LocalDate.of(localDateTime.getYear(), localDateTime.getMonth().firstMonthOfQuarter().plus(2), localDateTime.getMonth().firstMonthOfQuarter().plus(2).maxLength());
        LocalDateTime seasonStart = LocalDateTime.of(seasonStartDate, LocalTime.MIN);
        LocalDateTime seasonEnd = LocalDateTime.of(seasonEndDate, LocalTime.MAX);
        seasonTime.put("beginTime", seasonStart);
        seasonTime.put("endTime", seasonEnd);
        return seasonTime;
    }

    /**
     * 年 开始时间、结束时间
     *
     * @param localDateTime 输入日期
     * @return yearTime
     */
    public static Map yearTime(LocalDateTime localDateTime) {
        Map yearTime = new HashMap<String, LocalDateTime>();
        LocalDateTime yearStart = localDateTime.with(TemporalAdjusters.firstDayOfYear()).with(LocalTime.MIN);
        LocalDateTime yearEnd = localDateTime.with(TemporalAdjusters.lastDayOfYear()).with(LocalTime.MAX);
        yearTime.put("beginTime", yearStart);
        yearTime.put("endTime", yearEnd);
        return yearTime;
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值