New Java8 feature - date-time objects and some other features

Date Time Object

There are two types of operations on date and time:

  • Conversion: Conversion from string to timestamp
  • Calculate: Calculate the interval between two time points, the time point and the time period (Calculate next week N, next month D, last M month D, etc.)

Java8 provides three classes: LocalDate, LocalTime, and LocalDateTime in the form of 2020-01-01, 12:30:00, and 2020-01-01 12:30:00

create object

Getting class objects is very simple

LocalDate now = LocalDate.now();
LocalDate ld = LocalDate.of(2019, 1, 1);
// Get Year, Month and Day
now.getYear();
now.getMonthValue();	// If you call now.getMonth(), it will return you a capitalized English month word
now.getDayOfMonth();
// As the name should mean
getDayOfWeek();
getDayOfYear();	

// Set Year, Month and Day
LocalDate ld1 = ld.withYear(2021);		// 2021-01-01
LocalDate ld2 = ld.withMonth(12);		// 2019-12-01
LocalDate ld3 = ld.withDayOfMonth(12);	// 2019-12-12
// You may be wondering why not use the word set instead of with, since it's set
// Because the set operation generally changes the calling object itself and does not return a value.
// with creates a new object on the basis of the calling object, returns after setting the value, and does not change the calling object

// If you were the child who broke the casserole, you might ask: Why can't you change the calling object?
// Because LocalDate is final decorated (final is known as the Java world's knife of the uterus)
// Physically speaking, human beings cannot change time (traverse)

// If you have an anti-human calendar operation like ld.withMonth(13), of course it throws an exception

Both LocalTime and LocalDateTime have methods similar to LocalDate, which are not listed here (because I feel more and more like an api document)

Java8 API Official Documentation Direct Bus

Transformation

Conversion between date-time objects and strings:

// LocalDateTime object - >string
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
String dateTimeStr = now.format(dtf);
System.out.println(dateTimeStr);

// String - > LocalDateTime object
String str = "2022-01-30 12:15:20";
LocalDateTime dateTime = LocalDateTime.parse(str, dtf);
System.out.println(dateTime);

The DateTimeFormatter class also provides some ready-made formatter s, such as

DateTimeFormatter.BASIC_ISO_DATE ==> DateTimeFormatter.ofPattern("yyyyMMdd")
DateTimeFormatter.ISO_LOCAL_DATE ==> DateTimeFormatter.ofPattern("yyyy-MM-dd")
// More formatter s can be queried in api documents

The essence of learning is not what knowledge is remembered, but what triggers your thinking.- Michael Sandel

Conversion between date time and time stamp:

// LocalDateTime object - >timestamp
LocalDateTime now = LocalDateTime.now();
// Get the system default time zone
ZoneId systemDefaultZoneId = ZoneId.systemDefault();
Instant instant = now.atZone(systemDefaultZoneId).toInstant();
long timestamp = instant.toEpochMilli();
System.out.println(timestamp);


// Timestamp-> LocalDateTime object
long timestamp2 = 1578919583784L;
Instant instant2 = Instant.ofEpochMilli(timestamp2);
LocalDateTime dateTime2 = LocalDateTime.ofInstant(instant2, systemDefaultZoneId);
System.out.println(dateTime2);

"I don't understand why time stamping is such a hassle!"

Additionally, the conversion between java.util.Date and java.time.LocalDateTime requires Instant, neither of which provides a direct conversion method

// Get the system default time zone
ZoneId systemDefaultZoneId = ZoneId.systemDefault();
// Date to LocalDateTime
Date date3 = new Date();
Instant instant3 = date3.toInstant();
LocalDateTime localDateTime3 = LocalDateTime.ofInstant(instant3, systemDefaultZoneId);

// LocalDateTime to Date
Instant instant4 = now.atZone(systemDefaultZoneId).toInstant();
Date date4 = Date.from(instant4);

Also: LocalDateTime can consist of or be split into LocalDate and LocalTime

LocalDate nowLocalDate = LocalDate.now();
LocalTime nowLocalTime = LocalTime.now();
LocalDateTime nowLocalDateTime = LocalDateTime.of(nowLocalDate, nowLocalTime);

nowLocalDateTime.toLocalDate();
nowLocalDateTime.toLocalTime();

Calculation

Calculate the interval between the time point and the time point:

// Calculate the interval between dates and times
LocalTime startTime = LocalTime.now();
LocalTime endTime = startTime.plusHours(1).plusMinutes(50);
Duration duration = Duration.between(startTime, endTime);

// Interval seconds
duration.getSeconds();
// Interval days
duration.toDays();
// Hour interval
duration.toHours();
// Interval minutes
duration.toMinutes();

Duration.between(start, end) parameters can be LocalDateTime, LocalTime

It only returns an integer (the integer after the decimal is discarded, equivalent to floor()), not an hour and 50 minutes
If you want the form of y-year M months d days H hours m minutes s seconds, maybe you've assembled it yourself

// Calculate the interval between dates
LocalDate startDate = LocalDate.now();
LocalDate endDate = LocalDate.of(2031, 1, 1);
Period pe = Period.between(startDate, endDate);
pe.getYears();
pe.getMonths();
pe.getDays();

Point-in-time and time-period calculations:

	public LocalDateTime plusYears(long years) {
        LocalDate newDate = date.plusYears(years);
        return with(newDate, time);
    }

    public LocalDateTime plusMonths(long months) {
        LocalDate newDate = date.plusMonths(months);
        return with(newDate, time);
    }

    public LocalDateTime plusWeeks(long weeks) {
        LocalDate newDate = date.plusWeeks(weeks);
        return with(newDate, time);
    }

    public LocalDateTime plusDays(long days) {
        LocalDate newDate = date.plusDays(days);
        return with(newDate, time);
    }

    public LocalDateTime plusHours(long hours) {
        return plusWithOverflow(date, hours, 0, 0, 0, 1);
    }

    public LocalDateTime plusMinutes(long minutes) {
        return plusWithOverflow(date, 0, minutes, 0, 0, 1);
    }

    public LocalDateTime plusSeconds(long seconds) {
        return plusWithOverflow(date, 0, 0, seconds, 0, 1);
    }

    public LocalDateTime plusNanos(long nanos) {
        return plusWithOverflow(date, 0, 0, 0, nanos, 1);
    }

    public LocalDateTime minusYears(long years) {
        return (years == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-years));
    }

    public LocalDateTime minusMonths(long months) {
        return (months == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-months));
    }

    public LocalDateTime minusWeeks(long weeks) {
        return (weeks == Long.MIN_VALUE ? plusWeeks(Long.MAX_VALUE).plusWeeks(1) : plusWeeks(-weeks));
    }

    public LocalDateTime minusDays(long days) {
        return (days == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-days));
    }

    public LocalDateTime minusHours(long hours) {
        return plusWithOverflow(date, hours, 0, 0, 0, -1);
   }

    public LocalDateTime minusMinutes(long minutes) {
        return plusWithOverflow(date, 0, minutes, 0, 0, -1);
    }

    public LocalDateTime minusSeconds(long seconds) {
        return plusWithOverflow(date, 0, 0, seconds, 0, -1);
    }

    public LocalDateTime minusNanos(long nanos) {
        return plusWithOverflow(date, 0, 0, 0, nanos, -1);
    }

See, plus or minus years, months, days, hours, minutes, seconds, milliseconds

Just use it as you want, for example:

LocalDateTime now = LocalDateTime.now();

// Today, 30 years later (I'm still working, not retired)
LocalDateTime after30Years = now.plusYears(30L);
System.out.println(after30Years);

// 347 months later (I will be able to repay my loan)
LocalDateTime after348Months = now.plusMonths(347L);
System.out.println(after348Months);

// 11 days later (New Year's Eve)
LocalDateTime after10Days = now.plusDays(10L);
System.out.println(after10Days);

// 8 hours ago (I was at work)
LocalDateTime before8Hours = now.minusHours(8L);
System.out.println(before8Hours);

// 3 minutes ago (I started listening to Let it go)
LocalDateTime before3Before = now.minusMinutes(3L);
System.out.println(before3Before);

// 10 seconds ago (write down this code below)
LocalDateTime before10Second = now.minusSeconds(10L);
System.out.println(before10Second);

Actually, you don't have to distinguish between addition and subtraction, you can also subtract with plusXxx, as long as you pass in a negative parameter.

There is also a need, such as:

What day is Thanksgiving next year?(Thanksgiving is the fourth Thursday of November every year)
What day is next Friday?

This requires the time corrector Temporal Adjuster
Let me start with Temporal Adjuster, which is a functional interface with only one method, adjustInto

@FunctionalInterface
public interface TemporalAdjuster {
    Temporal adjustInto(Temporal temporal);
}

Temporal is an interface and LocalDateTime, LocalDate, LocalTime are all its implementation classes

There is a Temporal Adjuster adjuster in LocalDateTime, LocalDate, and LocalTime to fulfill the alternative needs mentioned above.

// Next Friday
LocalDateTime now = LocalDateTime.now();
LocalDateTime nextFriday = now.with(dt -> {
    // dt is a `Temporal` object, but is essentially the type of calling object
    LocalDateTime dateTime = (LocalDateTime) dt;
    // Unfortunately, there is no withDayOfWeek() method, otherwise it would be very convenient
    int dayOfWeekValue = dateTime.getDayOfWeek().getValue();
    int fridayValue = DayOfWeek.FRIDAY.getValue();
    return dateTime.plusWeeks(1L)
        		.plusDays(fridayValue - dayOfWeekValue);
});
System.out.println(nextFriday);

// Next year's Thanksgiving Day (the fourth Thursday in November)
LocalDate thanksGivingDay = LocalDate.now().with( t -> {
    LocalDate d = (LocalDate) t;
    // November 1, next year
    LocalDate newDate = d.plusYears(1L).withMonth(11).withDayOfMonth(1);

    int dayOfWeekValue = newDate.getDayOfWeek().getValue();
    int thursdayValue = DayOfWeek.THURSDAY.getValue();
    long plusWeeks = dayOfWeekValue > thursdayValue ? 4L : 3L;
    return newDate.plusWeeks(plusWeeks)
        			.plusDays(thursdayValue - dayOfWeekValue);
});
System.out.println(thanksGivingDay);

Temporal Adjusters actually provides many Temporal Adjuster objects, just as Collectors were compared to Collectors in the previous section of Stream.

Temporal Adjusters make it easy to meet these requirements

// Next Friday
LocalDateTime nextFriday = LocalDateTime.now().with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
System.out.println(nextFriday);

// Next year's Thanksgiving Day (the fourth Thursday in November)
LocalDate date = LocalDate.now().plusYears(1L).withMonth(11);
LocalDate thanksGivingDay = date.with(TemporalAdjusters.dayOfWeekInMonth(4, DayOfWeek.THURSDAY));
System.out.println(thanksGivingDay);

Note: The Temporal Adjusters.next (DayOfWeek day) method returns the next first Friday, not the next Friday as we normally understand it. For example, today, 2020-01-13 (Monday), then it returns Friday four days after 2020-01-17.

Temporal Adjusters provides more than just these two methods, but many others. API Documentation There are enough examples in this section to make it clear at a glance.

It is recommended that interested students read some source code, refer to Java8 code logic, and then use other programming languages to implement the same datetime operation, as datetime operations are often used in other programming languages, such as javaScript.

Other features

List it to show that I know them, but not that I understand them, so Let It Go!

Default method in interface

Static methods in interfaces

Optional class

Optional<String> op = Optional.of(str);

It identifies that the variable may be empty.

If a variable is likely to be empty, every time we use it before Java8, we must determine if it is empty.Now too!!

Optional does not avoid null pointer exceptions, only that the identity variable may be null.Make an analogy:

A mine was buried in the road ahead, but it was totally invisible from the surface. Unless we try to throw stones one step at a time, we may not have exploded one step at a time.Optional is used to identify the location of a mine. When we know where there is a mine, we walk around it so that we can safely pass through it

Optional also provides a function to set default values, which is fun.

Integer pageSize = null;
// Previously we set defaults
//pageSize = pageSize == null ? 10 : pageSize;
//System.out.println(pageSize);

// Use Optional to set default values
pageSize = Optional.ofNullable(pageSize)
    .orElse(20);
System.out.println(pageSize);

// Custom Default
Integer defaultPageSize = Optional.ofNullable(pageSize)
        .orElseGet(() -> {
            return new Integer(50);
        });

epilogue

The Java8 new feature series is over.

The most critical thing is to watch more Java Official API Documentation!!

I was thinking maybe we were overcorrected.The most common answer for all kinds of technical groups is: to ask Baidu!!Does Baidu know all about it?!

To be honest, in this day and age, everyone can post articles and comments on the network, and then everyone can reproduce them to each other, false can become true!
Reproduced without validation; valid at the time, now obsolete; a link to reproduce casually in the article...Meet the eye everywhere

Here's a short, eye-catching video about How Fake News Spreads

The most annoying thing is that Baidu searches for a keyword XXX and clicks in a blog post. The result is that there is no such keyword at all in the content of the article. So where is the keyword?
The keyword is in the title of the list of recommended articles on the website, so Baidu crawled it and displayed it in the search results.What the fuck!!

The blogs Baidu searches can look beyond them, but also at those frequently updated and reliable.

Reliable learning methods:

  1. Official latest API documentation
  2. Books/Videos (Pay attention to authoritativeness and timeliness)
  3. Frequently updated blogs

Don't Baidu easily!!

No
Thirteen original articles were published. Complimented 4. Visits 9675
Private letter follow

Tags: Java Programming Javascript network

Posted on Sun, 19 Jan 2020 21:12:18 -0500 by nagrgk