The paper

Time and date processing is a very frequently used logic in daily work. Java8 provides new time classes LocalDateTime and LocalDate to make date processing easier.

As a friendly reminder, it is better to use LocalDateTime by default in business development, because LocalDateTime can be easily converted to LocalDate, but LocalDate cannot be converted to LocalDateTime, and there will be no time and second data!!

This article summarizes the commonly used date processing methods and gives a brief explanation.

If you can write one line, don’t write two! The article will be updated continuously.

The instance

1. Obtain the character string of the current year, month and date

String ymd = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
Copy the code
  • DateTimeFormatter.ofPattern("yyyy-MM-dd")To modify the format of the retrieved date

2. Add or subtract N days, N months, N years from the current date

  • Get the date of last year, which is the year minus 1
LocalDate date = LocalDateTime.now().minusYears(1).toLocalDate();
Copy the code
  • Get the date one year from now, which is the year plus 1
LocalDate date = LocalDateTime.now().plusYears(1).toLocalDate();
Copy the code
  • All of the plus functionsplusThe prefix
  • In the same wayminusIt’s a function of days, weeks and months, very convenient

3. Get the day last week

  • Get last Week Monday
LocalDate monday = LocalDate.now().minusWeeks(1).with(DayOfWeek.MONDAY);
Copy the code
  • DayOfWeekIs an enumeration of days in java.time that can be used to obtain any day of the week
  • It’s still going to returnLocalDateObject for further processing

4. What day of the week, month, and year is it

LocalDateTime dateTime = LocalDateTime.now();
System.out.println(dateTime.getDayOfWeek());
System.out.println(dateTime.getDayOfMonth());
System.out.println(dateTime.getDayOfYear());
Copy the code

5. Get all the years in between

 public static List<Integer> getYearsBetweenTwoVar(LocalDate s, LocalDate e) {
        LocalDate tmp = s.plusYears(1);
        List<Integer> yearList = new ArrayList<>();
        while (tmp.isBefore(e)) {
            yearList.add(tmp.getYear());
            tmp = tmp.plusYears(1);
        }
        return yearList;
    }
Copy the code

6. Change the character string to LocalDateTime

LocalDateTime localDateTime = LocalDateTime.parse("The 2021-01-28 13:12:11", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
Copy the code

7. Date format conversion

String dateStr = LocalDateTime.parse("The 2021-03-07 10:58:30", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).format(DateTimeFormatter.ofPattern("Y year M month D day H hour M minute s second"));
Copy the code

The above content is a personal learning summary, if there is any inappropriate, welcome to point out in the comments