Java8 Date and Time API

LocalDate、LocalTime、Instant、Duration、Period

1.1 LocalDate and LocalTime

1.1.1LocalDate way to create and related methods use the sample

 @Test
        public void localDate() {
        LocalDate date = LocalDate.of(2019, 11, 1);
        int year = date.getYear();// 2019
        Month month = date.getMonth();// NOVEMBER
        int day = date.getDayOfMonth();// 1
        DayOfWeek dow = date.getDayOfWeek();// FRIDAY
        int len = date.lengthOfMonth();// 30
        boolean leap = date.isLeapYear();// false
        System.out.println(year + ", " + month + ", " + day + ", " + dow + ", " + len + ", " + leap);

        LocalDate date2 = LocalDate.now();
        int year2 = date2.get(ChronoField.YEAR);//2019
        int month2 = date2.get(ChronoField.MONTH_OF_YEAR);// 12
        int day2 = date2.get(ChronoField.DAY_OF_MONTH);// 14
        int dow2 = date2.get(ChronoField.DAY_OF_WEEK);//  6
        System.out.println(year2 + ", " + month2 + ", " + day2 + ", " + dow2);
        
        //不可以写成2019-11-1 会报DateTimeParseException
        LocalDate date3 = LocalDate.parse("2019-11-01");
        int year3 = date3.get(ChronoField.YEAR);//2019
        int month3 = date3.get(ChronoField.MONTH_OF_YEAR);// 11
        int day3 = date3.get(ChronoField.DAY_OF_MONTH);// 1
        int dow3 = date3.get(ChronoField.DAY_OF_WEEK);// 5
        System.out.println(year3 + ", " + month3 + ", " + day3 + ", " + dow3);
    }

1.1.1LocalTime way to create objects and associated methods example

    @Test
    public void localTime() {
        LocalTime time = LocalTime.of(11, 06, 23);
        int hour = time.getHour();
        int minute = time.getMinute();
        int second = time.getSecond();
        System.out.println(hour + ":" + minute + ":" + second);//  11:6:23

        LocalTime time2 = LocalTime.now();
        int hour2 = time2.get(ChronoField.HOUR_OF_DAY);
        int minute2 = time2.get(ChronoField.MINUTE_OF_HOUR);
        int second2 = time2.get(ChronoField.SECOND_OF_MINUTE);
        System.out.println(hour2 + ":" + minute2 + ":" + second2);//当前时间

        // 写13:9:22会报错,DateTimeParseException异常,可以传一个DateTimeFormatter自定义格式
        LocalTime time3 = LocalTime.parse("13:09:22");
        int hour3 = time3.get(ChronoField.HOUR_OF_DAY);
        int minute3 = time3.get(ChronoField.MINUTE_OF_HOUR);
        int second3 = time3.get(ChronoField.SECOND_OF_MINUTE);
        System.out.println(hour3 + ":" + minute3 + ":" + second3);// 13:9:22
    }

1.1.3LocalDateTime target three kinds of ways to create and related methods example

Test
    public void localDateTime() {
        LocalDate date = LocalDate.now();
        LocalTime time = LocalTime.now();
 
        // 创建LocalDateTime
        LocalDateTime dateTime = LocalDateTime.of(2019, 11, 1, 13, 32, 28);
        LocalDateTime dateTime2 = LocalDateTime.of(date, time);
        LocalDateTime dateTime3 = date.atTime(13, 32, 28);
        LocalDateTime dateTime4 = date.atTime(time);
        LocalDateTime dateTime6 = time.atDate(date);
 
        // 转化
        LocalDate date2 = dateTime2.toLocalDate();
        LocalTime time2 = dateTime2.toLocalTime();
    }

1.1.4 machine's date and time formats

The value of the number of seconds you can create an instance of a class by passing a representative of the static factory method ofEpochSecond. There is also a static factory method ofEpochSecond enhanced heavy-duty version, which receives the second in nanoseconds parameter values ​​for the number of seconds passed as a parameter to adjust the. Overloaded version will adjust the parameters of nanoseconds, to ensure the preservation of nanosecond slices between 0 and 999 999 999. This means that following these calls for ofEpochSecond factory method will return almost the same Instant objects:

Instant.ofEpochSecond(3);
Instant.ofEpochSecond(3, 0);
// 2 秒之后再加上100万纳秒(1秒)
Instant.ofEpochSecond(2, 1_000_000_000);
// 4秒之前的100万纳秒(1秒)
Instant.ofEpochSecond(4, -1_000_000_000);

As you already LocalDate and other dates for readability and design - time classes have seen, Instant class also supports static factory method now, it can help you get the time stamp of the current time. We want to emphasize that, Instant is designed for easy machine to use. It contains the number of second and nanosecond posed. Therefore, it can not handle those time units we are very easy to understand. This statement such as the following:

int day = Instant.now().get(ChronoField.DAY_OF_MONTH);

It throws this exception the following:

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: DayOfMonth

You can use Instant Duration and Period by category

1.1.5 Duration and definitions Period (time interval object)

  • Duration: LocalTime can pass two objects, localDateTime Instant object or objects
  • Period: Year, month, day modeling objects can pass two localDate
Duration d1 = Duration.between(time1, time2);
Duration d2 = Duration.between(dateTime1, dateTime2);
Duration d3 = Duration.between(instant1, instant2);

Because Instant LocalDateTime and are designed for different purposes, one is to facilitate people to read, and the other is to facilitate the processing machine, so you can not mix the two. If you attempt to create duration between the two types of objects, triggers a DateTimeException exception. If you need to year, month or day of the number of time units modeled on the way, you can use the Period class. The method uses the class factory between, you can get the duration between two LocalDate, as follows:

Period period = Period.between(LocalDate.of(2019, 11, 07), LocalDate.of(2019, 11, 07));

Period and Duration classes provide a number of convenient factory class, create an instance of the corresponding directly; in other words, as the following code that is no longer only in the form of two temporal difference objects to define them Object.

Duration threeMinutes = Duration.ofMinutes(3);
Duration fourMinutes = Duration.of(4, ChronoUnit.MINUTES);

Period tenDay = Period.ofDays(10);
Period threeWeeks = Period.ofWeeks(3);
Period twoYearsSixMonthsOneDay = Period.of(2, 6, 1);

Date manipulation parsing and formatting 1.2

1.2.1

  • In a more intuitive way to manipulate the properties LocalDate

The following code in all of the methods return a modified object properties. They will not modify the original object!

LocalDate date1 = LocalDate.of(2019, 11, 1);//2019-11-01
LocalDate date2 = date1.withYear(2020);//2020-11-01
LocalDate date3 = date2.withDayOfMonth(25);//2020-11-25
LocalDate date4 = date3.with(ChronoField.MONTH_OF_YEAR, 9);//2020-09-25
  • LocalDate modify the properties relative manner
@Test
public void editDateTime() {
        LocalDate date1 = LocalDate.of(2019, 11, 01);// 2019-11-01
        LocalDate date2 = date1.plusWeeks(1);// 2019-11-08
        LocalDate date3 = date2.minusYears(2);// 2017-11-08
        LocalDate date4 = date3.plus(6, ChronoUnit.MONTHS);// 2018-05-08
    }

1.2.3 TemporalAdjuster

@Test
public void adjust() {
        LocalDate date1 = LocalDate.of(2019, 11, 01);// 2019-11-01
        LocalDate date2 = date1.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));// 2019-11-03
        LocalDate date3 = date2.with(TemporalAdjusters.lastDayOfMonth());// 2019-11-30
    }

Class factory method TemporalAdjuster

1.2.4 custom formatted output date

The new version, we have a thread-safe class: DateTimeFormatterlook at the code

 @Test
    public void formatPrint() {
        LocalDate date = LocalDate.of(2019, 11, 01);
        String s1 = date.format(DateTimeFormatter.BASIC_ISO_DATE);// 20191101
        String s2 = date.format(DateTimeFormatter.ISO_LOCAL_DATE);// 2019-11-01

        LocalDate date1 = LocalDate.parse("20191101", DateTimeFormatter.BASIC_ISO_DATE);
        LocalDate date2 = LocalDate.parse("2019-11-01", DateTimeFormatter.ISO_LOCAL_DATE);

        // 自定义格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        String formattedDate = date.format(formatter);
        System.out.println(formattedDate);// 01/11/2019
        LocalDate date3 = LocalDate.parse(formattedDate, formatter);

        // 带时区的日期(本地化)
        DateTimeFormatter italianFormatter = DateTimeFormatter.ofPattern("d. MMMM yyyy", Locale.ITALIAN);
        String formattedDate2 = date.format(italianFormatter); 
        LocalDate date4 = LocalDate.parse(formattedDate2, italianFormatter);
    }

Guess you like

Origin www.cnblogs.com/thirtyYu/p/12041400.html