Java 1.8 不可变且线程安全的日期工具类
/**
* @author vzhenghuarui
* @date 2021-05-16 15:25
*/
public class LocalDateDemo {
public static void main(String[] args) {
LocalDate localDate = LocalDate.now();//当前日期
System.out.println("获取今年年份:" + localDate.getYear());
System.out.println("获取今年月份:" + localDate.getMonthValue());
System.out.println("获取当月的天数:" + localDate.getDayOfMonth());
System.out.println("获取今年的天数:" + localDate.getDayOfYear());
System.out.println("获取今天周几(枚举):" + localDate.getDayOfWeek());
System.out.println("获取今天周几(数值):" + localDate.getDayOfWeek().getValue());
int year = 1996;
System.out.println("获取今年日期的年份改为year年的日期:" + localDate.withYear(year));
int month = 11;
System.out.println("获取今年日期的月份改为month月的日期:" + localDate.withMonth(month));
int dayOfMonth = 31;
System.out.println("获取今年日期的天数改为dayOfMonth天的日期:" + localDate.withDayOfMonth(dayOfMonth));
Long count = 3L;
System.out.println("获取今天日期count年之前的日期:" + localDate.minusYears(count));
int monthCount = 3*12;
System.out.println("获取今天日期monthCount月之前的日期:" + localDate.minusMonths(monthCount));
int weekCount = 2;
System.out.println("获取今天日期weekCount周之前的日期:" + localDate.minusWeeks(weekCount));
int dayCount = 365;
System.out.println("获取今天日期dayCount天之前的日期:" + localDate.minusDays(dayCount));
System.out.println("获取今天日期count年之后的日期:" + localDate.plusYears(count));
System.out.println("获取今天日期monthCount月之后的日期:" + localDate.plusMonths(monthCount));
System.out.println("获取今天日期weekCount周之后的日期:" + localDate.plusWeeks(weekCount));
System.out.println("获取今天日期dayCount天之后的日期:" + localDate.plusDays(dayCount));
System.out.println("今年是否为润年:" + localDate.isLeapYear());
System.out.println("今年年份天数:" + localDate.lengthOfYear());
System.out.println("当月月份天数:" + localDate.lengthOfMonth());
System.out.println("日期比较:" + localDate.compareTo(localDate));
System.out.println("是否相等:" + localDate.isEqual(localDate));
System.out.println("是否在localDate之前:" + localDate.isBefore(localDate));
System.out.println("是否在localDate之后:" + localDate.isAfter(localDate));
// localDate 转 String
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
String date = formatter.format(localDate);
System.out.println(date);
// String 转 localDate
localDate = LocalDate.parse(date,formatter);
System.out.println(localDate);
}
}