本文主要总结localdate与localdatetime的用法,便于后续查找。
1、Localdate创建方法
//获取当前时间
LocalDate localDate = LocalDate.now();
//输入年月日设置时间
LocalDate localDate = LocalDate.of(year,month,day);
2、获取年月日星期几
int year = localDate.getYear();
int year = localDate.get(ChronoField.YEAR);
//注意getMonth方法返回的是Month类,可通过getValue方法获得一个long类型的值,然后可以强转为int类型进行使用
Month month = localDate.getMonth();
int month1 = localDate.get(ChronoField.MONTH_OF_YEAR);
int day = localDate.getDayOfMonth();
int day1 = localDate.get(ChronoField.DAY_OF_MONTH);
//注意getDayOfWeek方法返回的是DayOfWeek类,可通过getValue方法获得一个long类型的值,然后可以强转为int类型进行使用
DayOfWeek dayOfWeek = localDate.getDayOfWeek();
int dayOfWeek1 = localDate.get(ChronoField.DAY_OF_WEEK);
3、进行加减日期
LocalDate localDate = LocalDate.now();
//增减一年
localDate = localDate.plusYears(1);//增加
localDate = localDate.plus(1, ChronoUnit.YEARS);
localDate = localDate.minusYears(1);//减少
//减少一个月
localDate = localDate.minusMonths(1);//推荐
localDate = localDate.minus(1, ChronoUnit.MONTHS);
//减少一日
localDate = localDate.minusDays(1);//推荐
localDate = localDate.minus(1, ChronoUnit.DAYS);
//通过使用with方法进行修改
//修改年为2020
localDate = localDate.withYear(2020);
//修改为2020
localDate = localDate.with(ChronoField.YEAR, 2020);
4、日期转化
//指定一个字符串 转 时间
String wordGameStartTime ="2019-01-25 00:00:01";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss" );
LocalDateTime dateTime = LocalDateTime.parse(wordGameStartTime,formatter);
//时间 转 字符串
String format5 = localDateTime.format(formatter);
//localDateTime 转 LocalDate
LocalDate localDate = localDateTime.toLocalDate();
//localDateTime 转 LocalTime
LocalTime localTime = localDateTime.toLocalTime();
5、计算两个LocalDateTime之间的相差的天数
//获取当前时间
LocalDateTime now = LocalDateTime.now(); //2019-1-31
int days= (int)Duration.between(dateTime,now).toDays();
System.out.println(days); //6