一、Calender:

二、Date:

2.1)String to Date:

  1. public static Date stringToDate(String dateStr, String pattern) throws ParseException {
  2. SimpleDateFormat format = new SimpleDateFormat(pattern);
  3. return format.parse(dateStr);
  4. }
  5. //Test:
  6. System.out.println(stringToDate("20220101", "yyyyMMdd"));
  7. System.out.println(stringToDate("2022-01-01", "yyyy-MM-dd"));

2.2)Date to String:

  1. public static String dateToString(Date dateStr, String pattern) throws ParseException {
  2. SimpleDateFormat format = new SimpleDateFormat(pattern);
  3. return format.format(dateStr);
  4. }
  5. //Test:
  6. System.out.println(dateToString(new Date(), "yyyyMMdd"));
  7. System.out.println(dateToString(new Date(), "yyyy-MM-dd"));

2.3)加、减

  1. public static Date addDays(Date date, int n) {
  2. Calendar cal = Calendar.getInstance();
  3. //设置起时间
  4. cal.setTime(date);
  5. //增加天n天
  6. cal.add(Calendar.DATE, n);
  7. return cal.getTime();
  8. }
  9. //Test:
  10. System.out.println(addDays(new Date(), -1));
  11. System.out.println(addDays(new Date(), 1));

2.4)日期差

  1. public static int dateDifference(Date start, Date end) {
  2. Calendar cal = Calendar.getInstance();
  3. //设置起时间
  4. cal.setTime(start);
  5. int n = 0;
  6. for (;;) {
  7. //增加天1天
  8. cal.add(Calendar.DATE, 1);
  9. n = n + 1;
  10. if (cal.getTime().compareTo(end) == 0) {
  11. break;
  12. }
  13. }
  14. return n;
  15. }
  16. //Test:
  17. System.out.println(dateDifference(stringToDate("20220101", "yyyyMMdd"), stringToDate("20220102", "yyyyMMdd")));

2.5)获取两个日期中间的所有日期(包含起始日期)

  1. public static List<Date> getBetweenDate(Date start, Date end) {
  2. Set<Date> dateSet = new HashSet<>();
  3. Calendar cal = Calendar.getInstance();
  4. //设置起时间
  5. cal.setTime(start);
  6. int n = 0;
  7. for (;;) {
  8. dateSet.add(start);
  9. //增加天1天
  10. cal.add(Calendar.DATE, 1);
  11. n = n + 1;
  12. if (cal.getTime().compareTo(end) == 0) {
  13. break;
  14. }
  15. dateSet.add(cal.getTime());
  16. }
  17. dateSet.add(end);
  18. List<Date> dateList = new ArrayList<Date>(dateSet);
  19. Collections.sort(dateList);
  20. return dateList;
  21. }
  22. //Test:
  23. System.out.println(getBetweenDate(stringToDate("20220101", "yyyyMMdd"), stringToDate("20220102", "yyyyMMdd")));

2.6)获取一周的第一天、最后一天

2.7)获取一月的第一天、最后一天

2.8)获取一年的第一天、最后一天

2.8)大小比较

三、DateTime:

3.1)String to DateTime:

3.2)DateTime to String:

四、LocalDate:

4.1)String to LocalDate:

4.2)LocalDate to String:

五、LocalDateTime:

5.1)String to LocalDate:

5.2)LocalDate to String: