java8 LocalDateTime

2024-04-26 02:12
文章标签 java localdatetime

本文主要是介绍java8 LocalDateTime,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

LocalDateTime

java8使用了LocalDateTime和DateTimeFormatter。比之前的Date和Carlendar有所改进。
DateTimeFormatter是线程安全的。DateTimeFormatter中很多属性使用了final修饰。

LocalDate: 只能设置仅含年月日的格式,表示没有时区的日期, LocalDate是不可变并且线程安全的
LocalTime: 只能设置仅含时分秒的格式,表示没有时区的时间, LocalTime是不可变并且线程安全的
LocalDateTime: 可以设置含年月日时分秒的格式 , 表示没有时区的日期时间, LocalDateTime是不可变并且线程安全的

ZoneId: 时区ID,用来确定Instant和LocalDateTime互相转换的规则
Instant: 用来表示时间线上的一个点(瞬时)
Clock: 用于访问当前时刻、日期、时间,用到时区
Duration: 用秒和纳秒表示时间的数量(长短),用于计算两个日期的“时间”间隔

构建LocalDateTime对象:

	public  void generateLocalDate() {LocalDate date = LocalDate.of(2000, 1, 8);LocalDateTime dateTime = LocalDateTime.of(2020, 1, 8, 15, 16, 17);System.out.println("date:" + date);System.out.println("dateTime:" + dateTime);}

获取LocalDateTime的年月日:

	public  void getLocalDateTimeMonth() {LocalDateTime dateTime = LocalDateTime.of(2020, 1, 8, 15, 16, 17);int year=dateTime.getYear();int month=dateTime.getMonth().getValue();int day=dateTime.getDayOfMonth();System.out.println("dateTime对应的年份为:"+year);System.out.println("dateTime对应的月份为:"+month);System.out.println("dateTime对应的天数为:"+day);}

字符串String转LocalDateTime:

	public  void stringToTime() {DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");String datetimeText = "2020-04-01 23:59:59";LocalDateTime localDateTime = LocalDateTime.parse(datetimeText, formatter);// LocalDateTime的toString()方法,在日期和时间中间加入了"T"字符串System.out.println(localDateTime);}

LocalDateTime 转字符串String:

	public  void localDateTimeToString() {DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");LocalDateTime dateTime = LocalDateTime.of(2020, 1, 8, 15, 16, 17);String dateTimeStr = dateTime.format(formatter);System.out.println("dateTimeStr为:" + dateTime);}

LocalDateTime 转时间戳毫秒

      public static long getMillsByLocalDateTime(LocalDateTime localDateTime) {long mills = localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();return mills;}

时间戳毫秒转LocalDateTime

    public static LocalDateTime getLocalDateTimeByMills() {long mills = 1640419285000L;LocalDateTime result = new Date(mills).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();return result;}

Date转Instant:

        Instant instant= date.toInstant();

Instant转Date:

        Date date = Date.from(instant);

Date转LocalDateTime :

public static void dateToLocalDateTime(Date date) {Instant dateInstant = date.toInstant();LocalDateTime localDateTime = LocalDateTime.ofInstant(dateInstant, ZoneId.systemDefault());}

LocalDateTime转Date:

    public static Date parse(LocalDateTime localDateTime) {return Date.from(localDateTime.atZone( ZoneId.systemDefault()).toInstant());}

LocalDateTime 获取LocalDate:

LocalDate localDate = localDateTime.toLocalDate();

LocalDateTime 获取LocalTime:

LocalTime localTime = localDateTime.toLocalTime();

LocalDate

Date转LocalDate:

    public void dateToLocalDate(Date date) {Instant dateInstant = date.toInstant();LocalDate localDate = LocalDateTime.ofInstant(dateInstant, ZoneId.systemDefault()).toLocalDate();}

LocalDate转Date:

    public static Date parse(LocalDate localDate) {return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());}

localDate转String :

public static String localDateToString(Date date) {Instant dateInstant = date.toInstant();LocalDate localDate = LocalDateTime.ofInstant(dateInstant, ZoneId.systemDefault()).toLocalDate();// localDate转String DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");String localDateStr = localDate.format(formatter);System.out.println(localDateStr);return localDateStr;}

String转LocalDate:

public static void stringToLocalDate() {DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");String datetimeText = "2020-04-01";LocalDate localDate = LocalDate.parse(datetimeText, formatter);System.out.println(localDate);}

LocalDate获取年月日:

    int year = localDate.getYear();int monthValue = localDate.getMonthValue();int dayOfMonth = localDate.getDayOfMonth();

LocalDate修改年月日:

    public static void changeYearMonthDay() {LocalDate localDate = LocalDate.now();//修改年份LocalDate withYearResult = localDate.withYear(2020);//修改月份LocalDate withMonthResult = localDate.withMonth(5);//修改日LocalDate withDayResult = localDate.withDayOfMonth(20);System.out.println( withYearResult + "," + withMonthResult+ ","+ withDayResult);}

LocalDate比较日期大小compareTo:

compareTo()方法
在两边相等(=)的情况下返回 0
在左边大于(>)右边时返回 1 
在左边小于(<)右边时返回 -1

      public static void localDateCompareTo() {DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");String datetimeText = "2020-04-01";LocalDate localDate = LocalDate.parse(datetimeText, formatter);LocalDate nowDate = LocalDate.now();System.out.println(localDate);System.out.println("nowDate:"+nowDate);if (nowDate.compareTo(localDate) < 0) {System.out.println("nowDate小于"+ datetimeText);} else {System.out.println("nowDate大于等于"+ datetimeText);}}

LocalDate比较日期的前后:

after 只在大于(>)情况下才为true (相等时不会)
before 只在小于(<)情况下才为true (相等时不会)

public static void isBeforeAfter() {DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");String datetimeText = "2020-04-01";LocalDate localDate = LocalDate.parse(datetimeText, formatter);LocalDate nowDate = LocalDate.now();System.out.println(localDate);System.out.println("nowDate:"+nowDate);if (nowDate.isBefore(localDate)) {System.out.println(nowDate+ "在"+ datetimeText +"之前");} else {System.out.println(nowDate+ "在"+ datetimeText +"之后");}}

获取日期差距 / 获取日期时间间隔 :

public static void durationDateTime() {LocalDateTime date3 = LocalDateTime.now();LocalDateTime date4 = LocalDateTime.of(2018, 1, 13, 22, 30, 10);Duration duration = Duration.between(date3, date4);System.out.println(date3 + " 与 " + date4 + " 间隔  " + "\n"+ " 天 :" + duration.toDays() + "\n"+ " 时 :" + duration.toHours() + "\n"+ " 分 :" + duration.toMinutes() + "\n"+ " 毫秒 :" + duration.toMillis() + "\n"+ " 纳秒 :" + duration.toNanos() + "\n");}

日期时间计算:

	public void addMonthDay() {LocalDateTime dt = LocalDateTime.of(2020, 1, 26, 20, 30, 59);System.out.println(dt);// 加5天减3小时:LocalDateTime dt2 = dt.plusDays(5).minusHours(3);System.out.println(dt2); // 2019-10-31T17:30:59// 减1月:LocalDateTime dt3 = dt2.minusMonths(1);System.out.println(dt3); // 2019-09-30T17:30:59}

LocalTime

LocalTime获取时分秒:
        //获取小时int hour = localTime.getHour();int hour1 = localTime.get(ChronoField.HOUR_OF_DAY);//获取分int minute = localTime.getMinute();int minute1 = localTime.get(ChronoField.MINUTE_OF_HOUR);//获取秒int second = localTime.getMinute();int second1 = localTime.get(ChronoField.SECOND_OF_MINUTE);

参考资料:

https://www.liaoxuefeng.com/wiki/1252599548343744/1303871087444002
https://blog.csdn.net/weixin_38405253/article/details/100765007
https://www.jianshu.com/p/048ee8580639

这篇关于java8 LocalDateTime的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/936436

相关文章

Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码

《Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码》:本文主要介绍Java中日期时间转换的多种方法,包括将Date转换为LocalD... 目录一、Date转LocalDateTime二、Date转LocalDate三、LocalDateTim

如何配置Spring Boot中的Jackson序列化

《如何配置SpringBoot中的Jackson序列化》在开发基于SpringBoot的应用程序时,Jackson是默认的JSON序列化和反序列化工具,本文将详细介绍如何在SpringBoot中配置... 目录配置Spring Boot中的Jackson序列化1. 为什么需要自定义Jackson配置?2.

Java中使用Hutool进行AES加密解密的方法举例

《Java中使用Hutool进行AES加密解密的方法举例》AES是一种对称加密,所谓对称加密就是加密与解密使用的秘钥是一个,下面:本文主要介绍Java中使用Hutool进行AES加密解密的相关资料... 目录前言一、Hutool简介与引入1.1 Hutool简介1.2 引入Hutool二、AES加密解密基础

Spring Boot项目部署命令java -jar的各种参数及作用详解

《SpringBoot项目部署命令java-jar的各种参数及作用详解》:本文主要介绍SpringBoot项目部署命令java-jar的各种参数及作用的相关资料,包括设置内存大小、垃圾回收... 目录前言一、基础命令结构二、常见的 Java 命令参数1. 设置内存大小2. 配置垃圾回收器3. 配置线程栈大小

SpringBoot实现微信小程序支付功能

《SpringBoot实现微信小程序支付功能》小程序支付功能已成为众多应用的核心需求之一,本文主要介绍了SpringBoot实现微信小程序支付功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作... 目录一、引言二、准备工作(一)微信支付商户平台配置(二)Spring Boot项目搭建(三)配置文件

解决SpringBoot启动报错:Failed to load property source from location 'classpath:/application.yml'

《解决SpringBoot启动报错:Failedtoloadpropertysourcefromlocationclasspath:/application.yml问题》这篇文章主要介绍... 目录在启动SpringBoot项目时报如下错误原因可能是1.yml中语法错误2.yml文件格式是GBK总结在启动S

Spring中配置ContextLoaderListener方式

《Spring中配置ContextLoaderListener方式》:本文主要介绍Spring中配置ContextLoaderListener方式,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录Spring中配置ContextLoaderLishttp://www.chinasem.cntene

java实现延迟/超时/定时问题

《java实现延迟/超时/定时问题》:本文主要介绍java实现延迟/超时/定时问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java实现延迟/超时/定时java 每间隔5秒执行一次,一共执行5次然后结束scheduleAtFixedRate 和 schedu

Java Optional避免空指针异常的实现

《JavaOptional避免空指针异常的实现》空指针异常一直是困扰开发者的常见问题之一,本文主要介绍了JavaOptional避免空指针异常的实现,帮助开发者编写更健壮、可读性更高的代码,减少因... 目录一、Optional 概述二、Optional 的创建三、Optional 的常用方法四、Optio

Spring Boot项目中结合MyBatis实现MySQL的自动主从切换功能

《SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能》:本文主要介绍SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能,本文分步骤给大家介绍的... 目录原理解析1. mysql主从复制(Master-Slave Replication)2. 读写分离3.