时间日期处理是平时工做中使用很是频繁的逻辑,Java8中提供的新的时间类LocalDateTime和LocalDate,使日期处理能够更简单。java
友情提醒下,业务开发中最好默认使用LocalDateTime,由于LocalDateTime能够很方便的转换为LocalDate,可是LocalDate是不能够转为LocalDateTime的,会没有时分秒的数据!!!函数
本篇文章整理了经常使用的日期处理获取方式,并作简要说明。学习
能写一行的,就不写两行!文章会持续更新。code
String ymd = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
DateTimeFormatter.ofPattern("yyyy-MM-dd")
,修改获取的日期格式LocalDate date = LocalDateTime.now().minusYears(1).toLocalDate();
LocalDate date = LocalDateTime.now().plusYears(1).toLocalDate();
plus
前缀的minus
天,周,月的函数,很方便LocalDate monday = LocalDate.now().minusWeeks(1).with(DayOfWeek.MONDAY);
DayOfWeek
是java.time中的星期的枚举,可经过枚举值获取一周中的任一天LocalDate
对象,方便进一步处理LocalDateTime dateTime = LocalDateTime.now(); System.out.println(dateTime.getDayOfWeek()); System.out.println(dateTime.getDayOfMonth()); System.out.println(dateTime.getDayOfYear());
public static List<Integer> getYearsBetweenTwoVar(LocalDate s, LocalDate e) { LocalDate tmp = s.plusYears(1); List<Integer> yearList = new ArrayList<>(); while (tmp.isBefore(e)) { yearList.add(tmp.getYear()); tmp = tmp.plusYears(1); } return yearList; }
以上内容属我的学习总结,若有不当之处,欢迎在评论中指正orm