影视聚合站 时尚 文章内容

为什么建议使用你 LocalDateTime ,而不是 Date?

发布时间:2020-10-15 22:21:56来源:ImportNew

(给ImportNew加星标,提高Java技能)

转自:何甜甜在吗

链接:http://juejin.im/post/5d7787625188252388753eae

在项目开发过程中经常遇到时间处理,但是你真的用对了吗,理解阿里巴巴开发手册中禁用static修饰SimpleDateFormat吗

通过阅读本篇文章你将了解到:

为什么需要LocalDate、LocalTime、LocalDateTime【java8新提供的类】

java8新的时间API的使用方式,包括创建、格式化、解析、计算、修改

Date如果不格式化,打印出的日期可读性差

TueSep1009:34:04CST2019使用SimpleDateFormat对时间进行格式化,但SimpleDateFormat是线程不安全的SimpleDateFormat的format方法最终调用代码:

privateStringBufferformat(Datedate,StringBuffertoAppendTo,FieldDelegatedelegate){//Convertinputdatetotimefieldlistcalendar.setTime(date);booleanuseDateFormatSymbols=useDateFormatSymbols();for(inti=0;i>>8;intcount=compiledPattern[i++]&0xff;if(count==255){count=compiledPattern[i++]<<16;count|=compiledPattern[i++];}switch(tag){caseTAG_QUOTE_ASCII_CHAR:toAppendTo.append((char)count);break;caseTAG_QUOTE_CHARS:toAppendTo.append(compiledPattern,i,count);i+=count;break;default:subFormat(tag,count,delegate,toAppendTo,useDateFormatSymbols);break;}}returntoAppendTo;}calendar是共享变量,并且这个共享变量没有做线程安全控制。当多个线程同时使用相同的SimpleDateFormat对象【如用static修饰的SimpleDateFormat】调用format方法时,多个线程会同时调用calendar.setTime方法,可能一个线程刚设置好time值另外的一个线程马上把设置的time值给修改了导致返回的格式化时间可能是错误的。

在多并发情况下使用SimpleDateFormat需格外注意SimpleDateFormat除了format是线程不安全以外,parse方法也是线程不安全的。parse方法实际调用alb.establish(calendar).getTime()方法来解析,alb.establish(calendar)方法里主要完成了

重置日期对象cal的属性值

使用calb中中属性设置cal

返回设置好的cal对象

但是这三步不是原子操作

多线程并发如何保证线程安全-避免线程之间共享一个SimpleDateFormat对象,每个线程使用时都创建一次SimpleDateFormat对象=>创建和销毁对象的开销大-对使用format和parse方法的地方进行加锁=>线程阻塞性能差-使用ThreadLocal保证每个线程最多只创建一次SimpleDateFormat对象=>较好的方法

Date对时间处理比较麻烦,比如想获取某年、某月、某星期,以及n天以后的时间,如果用Date来处理的话真是太难了,你可能会说Date类不是有getYear、getMonth这些方法吗,获取年月日很Easy,但都被弃用了啊

只会获取年月日

创建LocalDate

//获取当前年月日LocalDatelocalDate=LocalDate.now();//构造指定的年月日LocalDatelocalDate1=LocalDate.of(2019,9,10);获取年、月、日、星期几

intyear=localDate.getYear();intyear1=localDate.get(ChronoField.YEAR);Monthmonth=localDate.getMonth();intmonth1=localDate.get(ChronoField.MONTH_OF_YEAR);intday=localDate.getDayOfMonth();intday1=localDate.get(ChronoField.DAY_OF_MONTH);DayOfWeekdayOfWeek=localDate.getDayOfWeek();intdayOfWeek1=localDate.get(ChronoField.DAY_OF_WEEK);LocalTime只会获取几点几分几秒

创建LocalTime

LocalTimelocalTime=LocalTime.of(13,51,10);LocalTimelocalTime1=LocalTime.now();获取时分秒

//获取小时inthour=localTime.getHour();inthour1=localTime.get(ChronoField.HOUR_OF_DAY);//获取分intminute=localTime.getMinute();intminute1=localTime.get(ChronoField.MINUTE_OF_HOUR);//获取秒intsecond=localTime.getSecond();intsecond1=localTime.get(ChronoField.SECOND_OF_MINUTE);LocalDateTime

获取年月日时分秒,等于LocalDate+LocalTime

创建LocalDateTime

LocalDateTimelocalDateTime=LocalDateTime.now();LocalDateTimelocalDateTime1=LocalDateTime.of(2019,Month.SEPTEMBER,10,14,46,56);LocalDateTimelocalDateTime2=LocalDateTime.of(localDate,localTime);LocalDateTimelocalDateTime3=localDate.atTime(localTime);LocalDateTimelocalDateTime4=localTime.atDate(localDate);获取LocalDate

LocalDatelocalDate2=localDateTime.toLocalDate();获取LocalTime

LocalTimelocalTime2=localDateTime.toLocalTime();Instant

获取秒数

创建Instant对象

Instantinstant=Instant.now();获取秒数

longcurrentSecond=instant.getEpochSecond();获取毫秒数

longcurrentMilli=instant.toEpochMilli();个人觉得如果只是为了获取秒数或者毫秒数,使用System.currentTimeMillis()来得更为方便

LocalDate、LocalTime、LocalDateTime、Instant为不可变对象,修改这些对象对象会返回一个副本

增加、减少年数、月数、天数等以

LocalDateTime为例

LocalDateTimelocalDateTime=LocalDateTime.of(2019,Month.SEPTEMBER,10,14,46,56);//增加一年localDateTime=localDateTime.plusYears(1);localDateTime=localDateTime.plus(1,ChronoUnit.YEARS);//减少一个月localDateTime=localDateTime.minusMonths(1);localDateTime=localDateTime.minus(1,ChronoUnit.MONTHS);通过

with修改某些值

//修改年为2019localDateTime=localDateTime.withYear(2020);//修改为2022localDateTime=localDateTime.with(ChronoField.YEAR,2022);还可以修改月、日

比如有些时候想知道这个月的最后一天是几号、下个周末是几号,通过提供的时间和日期API可以很快得到答案

LocalDatelocalDate=LocalDate.now();LocalDatelocalDate1=localDate.with(firstDayOfYear());比如通过firstDayOfYear()返回了当前日期的第一天日期,还有很多方法这里不在举例说明

LocalDatelocalDate=LocalDate.of(2019,9,10);Strings1=localDate.format(DateTimeFormatter.BASIC_ISO_DATE);Strings2=localDate.format(DateTimeFormatter.ISO_LOCAL_DATE);//自定义格式化DateTimeFormatterdateTimeFormatter=DateTimeFormatter.ofPattern("dd/MM/yyyy");Strings3=localDate.format(dateTimeFormatter);DateTimeFormatter默认提供了多种格式化方式,如果默认提供的不能满足要求,可以通过DateTimeFormatter的ofPattern方法创建自定义格式化方式

LocalDatelocalDate1=LocalDate.parse("20190910",DateTimeFormatter.BASIC_ISO_DATE);LocalDatelocalDate2=LocalDate.parse("2019-09-10",DateTimeFormatter.ISO_LOCAL_DATE);和SimpleDateFormat相比,DateTimeFormatter是线程安全的

LocalDateTime:Date有的我都有,Date没有的我也有,日期选择请PickMe

SpringBoot中应用LocalDateTime

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

publicclassLocalDateTimeConverterextendsJsonSerializer{@Overridepublicvoidserialize(LocalDateTimevalue,JsonGeneratorgen,SerializerProviderserializers)throwsIOException{gen.writeNumber(value.toInstant(ZoneOffset.of("+8")).toEpochMilli());}}并在

LocalDateTime字段上添加

@JsonSerialize(using=LocalDateTimeConverter.class)注解,如下:

@JsonSerialize(using=LocalDateTimeConverter.class)protectedLocalDateTimegmtModified;将LocalDateTime字段以指定格式化日期的方式返回给前端在

LocalDateTime字段上添加

@JsonFormat(shape=JsonFormat.Shape.STRING,pattern="yyyy-MM-ddHH:mm:ss")注解即可,如下:

@JsonFormat(shape=JsonFormat.Shape.STRING,pattern="yyyy-MM-ddHH:mm:ss")protectedLocalDateTimegmtModified;对前端传入的日期进行格式化在

LocalDateTime字段上添加

@DateTimeFormat(pattern="yyyy-MM-ddHH:mm:ss")注解即可,如下:

@DateTimeFormat(pattern="yyyy-MM-ddHH:mm:ss")protectedLocalDateTimegmtModified;

推荐阅读点击标题可跳转

看完本文有收获?请转发分享给更多人

关注「ImportNew」,提升Java技能

好文章,我在看❤️

© 2016-2017 ysjhz.com Inc.

站点统计| 举报| Archiver| 手机版| 小黑屋| 影视聚合站 ( 皖ICP备16004362号-2 )