Java8 日期和时间类的基本使用
前言
最近在重构之前的一个老项目,其中包含一个统计模块,需要把存储在MongoDB的数据通过接口显示在后端管理系统中。这些数据大多是以时间为单位进行存储,例如:collectionName_202009collectionName_20200910,在老系统中对时间的处理使用Date类,简单了解了其中的时间工具类,深感繁琐并决定使用Java8中的LocalDateTime和LocalDate重构此代码。
基本使用
1.获取当前时间
//2020-08-23T20:14:56.977 LocalDateTimelocalDateTime=LocalDateTime.now(); //2020-08-23 LocalDatelocalDate=LocalDate.now();
2.格式化时间
LocalDateTimelocalDateTime=LocalDateTime.now();
DateTimeFormatterlocalDateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss",Locale.SIMPLIFIED_CHINESE);
//2020-08-2320:20:29
StringtimeStr=localDateTime.format(localDateTimeFormatter);
LocalDatelocalDate=LocalDate.now();
DateTimeFormatterlocalDateFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
//2020-08-23
StringdateStr=localDate.format(localDateFormatter);
3.获取昨天、明天或者固定天数的时间
LocalDateTimelocalDateTime=LocalDateTime.now();
DateTimeFormatterlocalDateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss",Locale.SIMPLIFIED_CHINESE);
//今天
Stringtime=localDateTime.format(localDateTimeFormatter);
//昨天
LocalDateTimeyesterday=localDateTime.minusDays(1L);
StringyesterdayStr=yesterday.format(localDateTimeFormatter);
//后天
LocalDateTimetomorrow=localDateTime.plusDays(1L);
StringtomorrowStr=tomorrow.format(localDateTimeFormatter);
//天数加5
LocalDateTimetimePlus=localDateTime.plusDays(5L);
StringtimePlusStr=timePlus.format(localDateTimeFormatter);
//天数减5
LocalDateTimetimeMinus=localDateTime.minusDays(5L);
StringtimeMinusStr=timeMinus.format(localDateTimeFormatter);
在LocalDateTime的API中包含了对各个时间单位的增加和减少,如:
4.获取今天的开始时间和结束时间,精确到秒
DateTimeFormatterlocalDateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss",Locale.SIMPLIFIED_CHINESE);
//2020-08-2300:00:00
Stringstart=LocalDateTime.of(LocalDate.now(),LocalTime.MIN).format(localDateTimeFormatter);
//2020-08-2323:59:59
Stringend=LocalDateTime.of(LocalDate.now(),LocalTime.MAX).format(localDateTimeFormatter);
//这里的LocalDate.now()表示获取今天的开始时间和结束时间,也可以换做任何一天
5.获取当月的第一天和最后一天
//这里使用LocalDate来获取日期
DateTimeFormatterlocalDateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd",Locale.SIMPLIFIED_CHINESE);
LocalDatelocalDate=LocalDate.now();
LocalDatefirstDay=localDate.with(TemporalAdjusters.firstDayOfMonth());
LocalDatelastDay=localDate.with(TemporalAdjusters.lastDayOfMonth());
6.将时间字符串转为时间或日期
DateTimeFormatterformatter=DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss",Locale.SIMPLIFIED_CHINESE);
Stringstr="2018-08-0920:10:10";
LocalDateTimelocalDateTime=LocalDateTime.parse(str,formatter);
LocalDatelocalDate=LocalDate.parse(str,formatter);
7.计算日期间隔
DateTimeFormatterformatter=DateTimeFormatter.ofPattern("yyyy-MM-dd",Locale.SIMPLIFIED_CHINESE);
Stringstr="2020-09-02";
LocalDatelocalDate=LocalDate.parse(str,formatter);
longuntil=LocalDate.now().until(localDate,ChronoUnit.DAYS);
以上就是Java8日期和时间类的基本使用的详细内容,更多关于Java日期和时间类的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。