LocalDateTime(LocalDate、LocalTime)用法总结

2024-05-10 00:08

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

1. 为什么使用LocalDateTime?

(1)Date类及时间格式化SimpleDateFormat类线程不安全,LocalDateTime类及其时间格式化DateTimeFormatter类线程安全。
(2)Date类可读性差,LocalDateTime类可读性友好。
(3)Date的方法被弃用等原因。

2. 具体使用方式

引用的类主要是java.time.xxx包里的:

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.Period;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;/*** @Description* @author xxx* @date 2020-04-11 16:41:34*/
public class LocalDateTimeTest {public static void main(String[] args) {

// 1.LocalDate获取当前日期,LocalTime获取当前时间

LocalDate nowDate = LocalDate.now();
System.out.println("结果:" + nowDate);// 结果:2020-04-11
LocalTime nowTime = LocalTime.now();
System.out.println("结果:" + nowTime);// 结果:18:51:28.986

// 2.LocalDateTime获取当前日期和时间

LocalDateTime nowDateTime = LocalDateTime.now();                    
System.out.println("结果:" + nowDateTime);// 结果:2020-04-11T16:49:16.14

// 3.获取秒数

Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));                                           
System.out.println("结果:" + second);// 结果:1586595065     

// 4.获取毫秒数

Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();                           
System.out.println("结果:" + milliSecond);// 结果:1586595065304         

// 5.LocalDateTime与String互转

// 时间转字符串格式化                                                                                                    
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");                                 
String dateTime1 = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);                                    
System.out.println("结果:" + dateTime1);// 结果:20200411165517709                                                   // 时间格式化2                                                                                                       
LocalDate localDate2 = LocalDate.of(2019, 9, 10);                                                               
String s1 = localDate2.format(DateTimeFormatter.BASIC_ISO_DATE);                                                
String s2 = localDate2.format(DateTimeFormatter.ISO_LOCAL_DATE);                                                
// 自定义格式化                                                                                                       
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");                                              
String s3 = localDate2.format(dtf);                                                                             
// 时间格式化2:2019-09-10 20190910 2019-09-10 10/09/2019                                                             
System.out.println("时间格式化2:" + localDate2 + "  " + s1 + "  " + s2 + "  " + s3);                                 // 字符串转时间                                                                                                       
String dateTimeStr = "2018-07-28 14:11:15";                                                                     
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");                                      
LocalDateTime dateTime2 = LocalDateTime.parse(dateTimeStr, df);                                                 
System.out.println("结果:" + dateTime2);// 结果:2018-07-28T14:11:15      

// 6.Date与LocalDateTime互转

// 将java.util.Date 转换为java8 的java.time.LocalDateTime,默认时区为东8区                                                   
Date date = new Date();                                                                                         
LocalDateTime localDateTime = date.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();                 
System.out.println("结果:" + localDateTime);// 结果:2020-04-11T17:09:20.655                                         // 将java8 的 java.time.LocalDateTime 转换为 java.util.Date,默认时区为东8区                                                 
Date date2 = Date.from(localDateTime.toInstant(ZoneOffset.of("+8")));                                           
System.out.println("结果:" + date2);// 结果:Sat Apr 11 17:10:47 CST 2020       

// 7.LocalDateTime格式化

LocalDateTime time = LocalDateTime.now();                                                                       
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");                                    
String strDate = dtf2.format(time);                                                                             
System.out.println("结果:" + strDate);// 结果:2020-04-11 17:12:45    

// 8.LocalDate指定年月日,获取年、月、日、周次

LocalDate someDate = LocalDate.of(2020, 4, 11);                                                                 
// 年                                                                                                            
int year = someDate.getYear();                                                                                  
int year1 = someDate.get(ChronoField.YEAR);                                                                     
// 月                                                                                                            
Month month = someDate.getMonth();                                                                              
int month1 = someDate.get(ChronoField.MONTH_OF_YEAR);                                                           
// 日                                                                                                            
int day = someDate.getDayOfMonth();                                                                             
int day1 = someDate.get(ChronoField.DAY_OF_MONTH);                                                              
// 周                                                                                                            
DayOfWeek dayOfWeek = someDate.getDayOfWeek();                                                                  
int dayOfWeek1 = someDate.get(ChronoField.DAY_OF_WEEK);                                                         
// 结果:日期:2020-04-11,年:2020==2020,月:APRIL==4                                                                     
// 日:11==11,周:SATURDAY==6                                                                                       
System.out.println("日期:" + someDate + ",年:" + year + "==" + year1 + ",月:" + month + "==" + month1);             
System.out.println("日:" + day + "==" + day1 + ",周:" + dayOfWeek + "==" + dayOfWeek1);                

// 9.LocalTime某个时间的时分秒

LocalTime someTime = LocalTime.of(13, 51, 10);                                                                  
// 获取小时                                                                                                         
int hour = someTime.getHour();                                                                                  
int hour1 = someTime.get(ChronoField.HOUR_OF_DAY);                                                              
// 获取分                                                                                                          
int minute = someTime.getMinute();                                                                              
int minute1 = someTime.get(ChronoField.MINUTE_OF_HOUR);                                                         
// 获取秒                                                                                                          
int second1 = someTime.getSecond();                                                                             
int second2 = someTime.get(ChronoField.SECOND_OF_MINUTE);                                                       
// 时间:13:51:10,时:13==13,分:51==51                                                                                
// 秒:10==10                                                                                                     
System.out.println("时间:" + someTime + ",时:" + hour + "==" + hour1 + ",分:" + minute + "==" + minute1);           
System.out.println("秒:" + second1 + "==" + second2);       

// 10.获取年月日和时分秒

LocalDateTime ldt = LocalDateTime.of(2018, Month.SEPTEMBER, 10, 14, 46, 56);                                    
LocalDateTime ldt2 = LocalDateTime.of(someDate, someTime);                                                      
LocalDateTime ldt3 = someDate.atTime(someTime);                                                                 
LocalDateTime ldt4 = someTime.atDate(someDate);                                                                 
// --2019-09-10T14:46:56--2020-04-11T13:51:10--2020-04-11T13:51:10--2020-04-11T13:51:10                         
System.out.println("--" + ldt + "--" + ldt2 + "--" + ldt3 + "--" + ldt4);                                       LocalDate ld2 = ldt.toLocalDate();                                                                              
LocalTime lt2 = ldt.toLocalTime();                                                                              
// --2019-09-10--14:46:56                                                                                       
System.out.println("--" + ld2 + "--" + lt2);            

// 11.日期计算

// 增加一年                                                                                                         
ldt2 = ldt.plusYears(1);                                                                                        
ldt3 = ldt.plus(1, ChronoUnit.YEARS);                                                                           
// 减少一个月                                                                                                        
ldt4 = ldt.minusMonths(1);                                                                                      
ldt = ldt.minus(1, ChronoUnit.MONTHS);                                                                          System.out.println("日期计算--" + ldt2 + "--" + ldt3 + "--" + ldt4 + "--" + ldt);                                   // 修改年为2019                                                                                                     
ldt2 = ldt.withYear(2020);                                                                                      
// 修改为2022                                                                                                      
ldt3 = ldt.with(ChronoField.YEAR, 2022);                                                                        
// 改年--2020-08-10T14:46:56--2022-08-10T14:46:56                                                                 
System.out.println("改年--" + ldt2 + "--" + ldt3);        

// 12.日期计算

// 比如有些时候想知道这个月的最后一天是几号、下个周末是几号,通过提供的时间和日期API可以很快得到答案 。                                                         
// TemporalAdjusters提供的各种日期时间格式化的静态类,比如firstDayOfYear是当前日期所属年的第一天                                               
LocalDate localDate = LocalDate.now();                                                                          
LocalDate localDate1 = localDate.with(TemporalAdjusters.firstDayOfYear());                                      
// 日期计算2:2020-04-11--2020-01-01                                                                                 
System.out.println("日期计算2:" + localDate + "--" + localDate1);                   

// 13.Instant 获取秒数

Instant instant = Instant.now();                                                                                
// 获取秒数                                                                                                         
long currentSecond = instant.getEpochSecond();                                                                  
// 获取毫秒数                                                                                                        
long currentTimeMillis = instant.toEpochMilli();                                                                
long currentTimeMillis2 = System.currentTimeMillis();                                                           
// Instant--2020-04-11T12:49:02.957Z--1586609342--1586609342957==1586609342957                                  
System.out.println( "Instant--" + instant + "--" + currentSecond + "--" + currentTimeMillis + "==" + currentTimeMillis2);   

// 14.间隔计算

// 使用Duration进行 day,hour,minute,second等的计算                                                                      
Duration duration = Duration.between(ldt, nowDateTime);                                                         
duration.toDays();                                                                                              
duration.toHours();                                                                                             
duration.toMinutes();                                                                                           
System.out.println("间隔天:" + duration.toDays() + ",间隔小时:" + duration.toHours() + ",间隔分钟:" + duration.toMinutes()); 
// 使用Period进行Year,Month的计算                                                                                      
Period period = Period.between(ldt.toLocalDate(), nowDateTime.toLocalDate());                                   
period.getYears();                                                                                              
period.getMonths();                                                                                             
period.toTotalMonths();                                                                                         
System.out.println("间隔年:" + period.getYears() + ",间隔月:" + period.getMonths() + ",间隔总月:" + period.toTotalMonths());
    }}

3. SpringBoot中应用LocalDateTime

将LocalDateTime字段以时间戳的方式返回给前端 添加日期转化类

public class LocalDateTimeConverter extends JsonSerializer<LocalDateTime> {@Overridepublic void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {gen.writeNumber(value.toInstant(ZoneOffset.of("+8")).toEpochMilli());}
}

并在LocalDateTime字段上添加@JsonSerialize(using = LocalDateTimeConverter.class)注解,如下:

@JsonSerialize(using = LocalDateTimeConverter.class)
protected LocalDateTime gmtModified;

将LocalDateTime字段以指定格式化日期的方式返回给前端 在LocalDateTime字段上添加@JsonFormat(shape=JsonFormat.Shape.STRING, pattern=“yyyy-MM-dd HH:mm:ss”)注解即可
(或者@JsonFormat(timezone = “GMT+8”, pattern = “yyyy-MM-dd HH:mm:ss”)注解),如下:

@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
protected LocalDateTime gmtModified;

对前端传入的日期进行格式化 在LocalDateTime字段上添加@DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)注解即可,如下:

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
protected LocalDateTime gmtModified;

4. 参考资料

(1)为什么建议使用你LocalDateTime,而不是Date?
(2)JDK8的LocalDateTime用法
(3)java时间对象Date,Calendar和LocalDate/LocalDateTime

这篇关于LocalDateTime(LocalDate、LocalTime)用法总结的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

golang panic 函数用法示例详解

《golangpanic函数用法示例详解》在Go语言中,panic用于触发不可恢复的错误,终止函数执行并逐层向上触发defer,最终若未被recover捕获,程序会崩溃,recover用于在def... 目录1. panic 的作用2. 基本用法3. recover 的使用规则4. 错误处理建议5. 常见错

前端知识点之Javascript选择输入框confirm用法

《前端知识点之Javascript选择输入框confirm用法》:本文主要介绍JavaScript中的confirm方法的基本用法、功能特点、注意事项及常见用途,文中通过代码介绍的非常详细,对大家... 目录1. 基本用法2. 功能特点①阻塞行为:confirm 对话框会阻塞脚本的执行,直到用户作出选择。②

Rust格式化输出方式总结

《Rust格式化输出方式总结》Rust提供了强大的格式化输出功能,通过std::fmt模块和相关的宏来实现,主要的输出宏包括println!和format!,它们支持多种格式化占位符,如{}、{:?}... 目录Rust格式化输出方式基本的格式化输出格式化占位符Format 特性总结Rust格式化输出方式

Python中多线程和多进程的基本用法详解

《Python中多线程和多进程的基本用法详解》这篇文章介绍了Python中多线程和多进程的相关知识,包括并发编程的优势,多线程和多进程的概念、适用场景、示例代码,线程池和进程池的使用,以及如何选择合适... 目录引言一、并发编程的主要优势二、python的多线程(Threading)1. 什么是多线程?2.

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

Python itertools中accumulate函数用法及使用运用详细讲解

《Pythonitertools中accumulate函数用法及使用运用详细讲解》:本文主要介绍Python的itertools库中的accumulate函数,该函数可以计算累积和或通过指定函数... 目录1.1前言:1.2定义:1.3衍生用法:1.3Leetcode的实际运用:总结 1.1前言:本文将详

MyBatis-Flex BaseMapper的接口基本用法小结

《MyBatis-FlexBaseMapper的接口基本用法小结》本文主要介绍了MyBatis-FlexBaseMapper的接口基本用法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具... 目录MyBATis-Flex简单介绍特性基础方法INSERT① insert② insertSelec

springboot日期格式化全局LocalDateTime详解

《springboot日期格式化全局LocalDateTime详解》文章主要分析了SpringBoot中ObjectMapper对象的序列化和反序列化过程,并具体探讨了日期格式化问题,通过分析Spri... 目录分析ObjectMapper与jsonSerializer结论自定义日期格式(全局)扩展利用配置

Python中连接不同数据库的方法总结

《Python中连接不同数据库的方法总结》在数据驱动的现代应用开发中,Python凭借其丰富的库和强大的生态系统,成为连接各种数据库的理想编程语言,下面我们就来看看如何使用Python实现连接常用的几... 目录一、连接mysql数据库二、连接PostgreSQL数据库三、连接SQLite数据库四、连接Mo

深入解析Spring TransactionTemplate 高级用法(示例代码)

《深入解析SpringTransactionTemplate高级用法(示例代码)》TransactionTemplate是Spring框架中一个强大的工具,它允许开发者以编程方式控制事务,通过... 目录1. TransactionTemplate 的核心概念2. 核心接口和类3. TransactionT