Date processing
Before Java 8, it was not very convenient to operate the date. Some places need to be programmed and implemented by yourself. In Java 8, many classes about date processing are added under the java.time package. Through these classes, developers can operate the date more easily. These classes are all final decorated and thread safe.
Class LocalDate
LocalDate class can only operate date related data, not time
//LocalDate class //LocalDate class can only operate on date related data without time LocalDate date1 = LocalDate.now(); System.out.println(date1); //2019-03-11 int year = date1.getYear(); int month = date1.getMonthValue(); int day = date1.getDayOfMonth(); //format date String s1 = date1.format(DateTimeFormatter.ofPattern("YYYY year MM month DD day")); System.out.println(s1); //Judgement of leap year boolean leap = date1.isLeapYear(); //How many days to get the month int len = date1.lengthOfMonth(); System.out.println(len);
Class LocalTime
The LocalTime class can only operate on time-related data, excluding dates
LocalTime time1 = LocalTime.now().withNano(0); System.out.println(time1); //Setup time LocalTime time2 = LocalTime.of(6, 30, 20); System.out.println(time2); LocalTime time3 = LocalTime.parse("18:20:20"); System.out.println(time3);
LocalDateTime class
The LocalDateTime class can process date and time data
//LocalDateTime class LocalDateTime time = LocalDateTime.now(); System.out.println("The current time is:"+time);
Duration and Period
The Duration class is used to get the time difference between two localtimes
The Period class is used to get the date when two localdates differ
//Calculate the time difference between two localtimes LocalTime time7 = LocalTime.of(7, 20); LocalTime time8 = LocalTime.of(7, 30); Duration duration = Duration.between(time7, time8); System.out.println("The number of time seconds between the two is:"+duration.getSeconds());
//How many years, months and days have passed since the founding of the people's Republic of China //Founding date LocalDate begin = LocalDate.of(1949, 10, 1); //Today's date LocalDate end = LocalDate.now(); System.out.println("The motherland has been established"); System.out.println(Period.between(begin, end).getYears()+"year"); System.out.println(Period.between(begin, end).getMonths()+"month"); System.out.println(Period.between(begin, end).getDays()+"day");