1. LocalDateTime now = LocalDateTime.now();
    2. //获取当前日期
    3. System.out.println("now = " + now);//now = 2020-01-27T22:23:33.320
    4. System.out.println("now.getYear() = " + now.getYear());//now.getYear() = 2019
    5. //注意获取月份的两个方法的区别
    6. System.out.println("now.getMonth() = " + now.getMonth());//now.getMonth() = JANUARY
    7. System.out.println("now.getMonthValue() = " + now.getMonthValue());//now.getMonthValue() = 1
    8. System.out.println("now.getDayOfMonth() = " + now.getDayOfMonth());//now.getDayOfMonth() = 27
    9. System.out.println("now.getHour() = " + now.getHour());
    10. System.out.println("now.getMinute() = " + now.getMinute());
    11. System.out.println("now.getSecond() = " + now.getSecond());
    12. //构造指定日期,eg.2020-08-08
    13. LocalDate diyDate = LocalDate.of(2020, 8, 8);
    14. System.out.println("diyDate = " + diyDate);
    15. //构造指定时间,eg.2020-08-08 00:00:00
    16. LocalDateTime diyTime = LocalDateTime.of(2020, 8, 8, 0, 0, 0);
    17. System.out.println("diyTime = " + diyTime);//diyDate = 2020-08-08T00:00
    18. //修改日期
    19. //①增加/减少几个月
    20. LocalDateTime localDateTime = LocalDateTime.now();
    21. System.out.println("localDateTime = " + localDateTime);//localDateTime = 2020-01-27T22:37:05.546
    22. //下个月,plusMonth()
    23. localDateTime = localDateTime.plusMonths(1);
    24. System.out.println("localDateTime = " + localDateTime);//localDateTime = 2020-02-27T22:37:05.546
    25. //上个月,-1
    26. localDateTime = localDateTime.minusMonths(1);
    27. //或者使用 plusMonth(-1)
    28. //localDateTime = localDateTime.plusMonths(-1);
    29. System.out.println("localDateTime = " + localDateTime);//localDateTime = 2020-01-27T22:37:05.546
    30. //②修改到指定日期
    31. localDateTime = localDateTime.withYear(2200);
    32. System.out.println("localDateTime = " + localDateTime);//localDateTime = 2200-01-27T22:43:26.722
    33. //格式化日期
    34. //①自定义日期格式
    35. String diyFormatDate = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    36. System.out.println("diyFormatDate = " + diyFormatDate);//formatDate = 2020-01-27 22:47:21
    37. //②几种基本格式
    38. String format = now.format(DateTimeFormatter.ISO_DATE);
    39. System.out.println("format = " + format);//format = 2020-01-27
    40. format = now.format(DateTimeFormatter.BASIC_ISO_DATE);
    41. System.out.println("format = " + format);//format = 20200127
    42. //解析日期
    43. LocalDateTime parse = LocalDateTime.parse("2020-01-27 22:47:21", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    44. System.out.println("parse = " + parse);//parse = 2020-01-27T22:47:21