码迷,mamicode.com
首页 > 编程语言 > 详细

java8中的常用日期操作

时间:2020-02-11 19:22:27      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:today   增加   方法   code   bsp   value   format   boolean   between   

java8有很多时间上的新api,在操作时间的时候很好用,这儿算是个备忘录吧,(补充中。。。)

 

定位某个时间:of方法

LocalDateTime dateTime = LocalDateTime.of(2020, 2, 11, 13, 15, 12);
LocalDate date = LocalDate.of(2020, 2, 11);

 

计算两个时间的差值(day,hour,minute等)

LocalDateTime dateTime1 = LocalDateTime.of(2020, 2, 11, 13, 15, 12);
LocalDateTime dateTime2 = LocalDateTime.of(2020, 3, 11, 13, 15, 12);
Duration between = Duration.between(dateTime1, dateTime2);
System.out.println(between.toDays());
System.out.println(between.toHours());
System.out.println(between.toMinutes());

 

对某个时间进行增加或者减少

LocalDateTime dateTime = LocalDateTime.of(2020, 2, 11, 13, 15, 12);
LocalDateTime t1 = dateTime.plusDays(1);
System.out.println(t1);
LocalDateTime t2 = dateTime.plusMonths(1);
System.out.println(t2);

 

获取某个时间是否为闰年

  

LocalDateTime dateTime = LocalDateTime.of(2020, 2, 11, 13, 15, 12);
boolean leapYear = dateTime.toLocalDate().isLeapYear();
System.out.println(leapYear);
boolean leap = Year.of(2016).isLeap();

 

获取某月第一天,最后一天以及一共有多少天,以及当前月是第几月

LocalDateTime dateTime = LocalDateTime.of(2020, 2, 11, 13, 15, 12);
YearMonth month = YearMonth.from(dateTime);
LocalDate begin = month.atDay(1);
int length = month.lengthOfMonth();
LocalDate end = month.atEndOfMonth(); 
int monthValue = month.getMonthValue();

 

格式化日期

LocalDateTime dateTime = LocalDateTime.of(2020, 2, 11, 13, 15, 12);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
String r = dateTime.format(formatter);
TemporalAccessor parse = formatter.parse(r);
LocalDate from = LocalDate.from(parse);

 

java8中的常用日期操作

标签:today   增加   方法   code   bsp   value   format   boolean   between   

原文地址:https://www.cnblogs.com/hetutu-5238/p/12296094.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!