LocalDate和LocalDateTime常用API
LocalDate
1.获取当前时间
LocalDate today = LocalDate.now();
2.获取当前月份
LocalDate today = LocalDate.now();
int month = today.getMonthValue();
3.获取当前日期
LocalDate today = LocalDate.now();
int day = today.getDayOfMonth();
4.获取指定日期
LocalDate date = LocalDate.parse("2020-01-01"); #以获取2020年01月01日为例
5.获取当前时间前/后X天的日期
LocalDate data = LocalDate.now().plusDays(±X);
获取前一天的日期
LocalDate data = LocalDate.now().plusDays(-1);
获取后一天的日期
LocalDate data = LocalDate.now().plusDays(+1);
6.获取本周周一的日期
LocalDate today = LocalDate.now();
LocalDate firstDay = today.with(DayOfWeek.MONDAY);
7.获取本月第一天的日期
LocalDate today = LocalDate.now();
LocalDate firstDay = today.with(TemporalAdjusters.firstDayOfMonth());
8.获取本月的总天数
LocalDate today = LocalDate.now();
int TotalDays = today.withMonth(today.getMonthValue()).lengthOfMonth();
9.获取当前年份的第一天
LocalDate today = LocalDate.now();
LocalDate firsDay = today.with(TemporalAdjusters.firstDayOfYear());
10.LocalDate和String相互转换
LocalDate转String
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate today = LocalDate.now();
String dateStr = today.format(df);
String转LocalDate
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String str = "2020-01-01";
LocalDate date = LocalDate.parse(str, fmt);
11.获取两个时间间隔中的每一天
List<String> list = new ArrayList<>();
long distance = ChronoUnit.DAYS.between(startDate, endDate); #传入开始时间和结束时间
if (distance < 1) {
return list;
}
Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).forEach(f -> list.add(f.toString()));
return list;
12.比较两个日期的大小
判断localDate1是否和localDate2相等,返回布尔值
boolean equal = localDate1.isEqual(localDate2);
判断localDate1是否在localDate2之前,返回布尔值
boolean before = localDate1.isBefore(localDate2);
判断localDate1是否在localDate2之后,返回布尔值
boolean after = localDate1.isAfter(localDate2);
LocalDateTime
1.获取当前时间
LocalDateTime today = LocalDateTime.now();
2.获取当前时间年、月、日、时、分、秒
LocalDateTime today = LocalDateTime.now();
int year = today.getYear(); #年
int month = today.getMonthValue(); #月
int day = today.getDayOfMonth(); #日
int hour = today.getHour(); #时
int minute = today.getMinute(); #分
int second = today.getSecond(); #秒
3.LocalDateTime和String相互转换
LocalDateTime转String
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime today = LocalDateTime.now();
String format = today.format(df);
String转LocalDateTime
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String str = "2020-01-01 11:11:11";
LocalDateTime data = LocalDateTime.parse(str, df);