java8中的常用日期操作

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中的常用日期操作)