Thinking Logic of computer programs (8)-Date and time API for Java

Source: Internet
Author: User
Tags epoch time time zones new set parse string

This section continues to explore the new features of Java 8, mainly the introduction of Java 8 on the date and time API enhancements, about the date and time, we have introduced two previous sections, 32 describes the Java 1.8 before the date and time API, the main class is the date and calendar, Due to its lack of design, the industry is widely used in a third-party class library joda-time, about Joda-time, we introduced in section 33. Java 1.8 has learned joda-time and introduced a new set of APIs, which are located under Package Java.time, and we will briefly introduce this new API.

Let's start with the date and time representation.

Represents a date and time

Basic concepts

We have introduced several basic concepts of date and time in section 32, which is briefly reviewed here.

    • Moment: All computer systems are represented by an integer, this integer is the number of milliseconds from 0:0 GMT, January 1, 1970, 0 seconds, can understand the moment is absolute time, it is independent of the time zone, different time zones for the same moment of interpretation, that is, date and time is not the same;
    • Time zone: At the same time, different regions of the world may be different times, time and time zone, a total of 24 time zones, the United Kingdom Greenwich is 0 time zone, Beijing is the East eight district, that is, Greenwich 1 o'clock in the morning, Beijing is the morning 9 points;
    • Almanac: We all know that China has the Gregorian and lunar calendar, the Gregorian calendar and the lunar calendar, different calendars, how many months a year, how many days a month, or even how many hours a day, these may not be the same, we mainly discuss the Gregorian calendar.

There are several classes in Java 8 that represent dates and times, mainly:

    • Instant: Indicates the moment, does not correspond directly to the month and day information, need to pass the time zone conversion
    • LocalDateTime: Represents a time zone-independent date and time information that does not correspond directly to the moment and needs to be converted by time zone
    • Localdate: Represents a time zone-independent date, with only date information and no time information compared to LocalDateTime
    • LocalTime: Indicates time zone-independent times, compared to LocalDateTime, only time information, no date information
    • Zoneddatetime: A date and time that represents a specific time zone
    • Zoneid/zoneoffset: Indicates the time zone

The analogy is more, but the concept is clearer, let's look at it one by one.

Instant

Instant represents the moment, gets the current moment, the code is:

Instant now = Instant.now ();

Instant can be created based on Epoch Time (ERA), for example, another code that gets the current moment can be:

Instant now = Instant.ofepochmilli (System.currenttimemillis ());

We know that date also represents a time when instant and date can be converted to each other through eras, for example, converting date to instant, code:

 Public Static Instant toinstant (date date) {    return  Instant.ofepochmilli (Date.gettime ());}

Convert instant to date and the code is:

 Public Static Date toDate (Instant Instant) {    returnnew  Date (Instant.toepochmilli ());}

Instant has a lot of time-based comparisons and computational methods, mostly more intuitive, we don't list.

LocalDateTime

LocalDateTime represents date and time information that is independent of the time zone, gets the current date and time for the system default time zone, with the code:

LocalDateTime Ldt = Localdatetime.now ();

You can also use information such as month and date to build localdatetime, for example, the July 11, 2017 20:45 5 seconds, the code can be:

LocalDateTime Ldt = localdatetime.of (2017, 7, 11, 20, 45, 5);

LocalDateTime There are many ways to get calendar information such as date and time of day and month, such as:

 Public int getYear ()  Public int Getmonthvalue ()  Public int GetDayOfMonth ()  Public int Gethour ()  Public int Getminute ()  Public int Getsecond ()

You can also get information about the day of the week, such as:

Public

DayOfWeek is an enumeration that has seven values, from Dayofweek.monday to DayOfWeek.Sunday.

LocalDateTime cannot be converted directly to moment instant, the conversion requires a parameter zoneoffset,zoneoffset to indicate a time zone difference relative to Greenwich, and Beijing is +08:00, for example, to convert a localdatetime to Beijing's moment, The method is:

 Public Static Instant tobeijinginstant (LocalDateTime ldt) {    return ldt.toinstant (Zoneoffset.of ("+08:00" ));}

Given a moment, using different time zones to interpret the calendar information is different, instant has a way to return a zoneddatetime according to the time zone:

 Public Zoneddatetime Atzone (ZoneID zone)

The default time zone is Zoneid.systemdefault (), so you can build ZoneID:

// Beijing Time Zone ZoneID Bjzone = Zoneid.of ("gmt+08:00")

Zoneoffset is a subclass of ZoneID that can be constructed according to the time zone difference.

Localdate/localtime

It can be thought that LocalDateTime is made up of two parts, part of date localdate, the other part is time localtime, and their usage is very intuitive, such as:

// represents July 11, 2017 Localdate ld = Localdate.of (7, one); // the current time by the system default time zone interpretation of the date Localdate now = localdate.now (); // means 21 points, 10 minutes, 34 seconds. LocalTime lt = localtime.of (+, ten,); // time that is interpreted by the system default time zone at the current time LocalTime time = Localtime.now ();

LocalDateTime is composed of Localdate and localtime, Localdate plus time can constitute localdatetime,localtime plus date can constitute localdatetime, such as:

LocalDateTime Ldt = Localdatetime.of (7, 5//2017-07-11//  20:45:05//localdate plus time, the result is 2017-07-11 21:18:39LocalDateTime ldt2 = ld.attime (+,-); // localtime Plus date, the result is 2016-03-24 20:45:05 LocalDateTime LDT3 = lt.atdate (Localdate.of (2016, 3, 24));

Zoneddatetime

Zoneddatetime represents the date and time for a specific time zone, gets the current date and time for the system default time zone, with the code:

Zoneddatetime ZDT = Zoneddatetime.now ();

Localdatetime.now () is also the current date and time to get the default time zone, what's the difference? LocalDateTime does not log the time zone information, but only records the date and minute seconds, and so on, and Zoneddatetime in addition to recording calendar information, but also record the time zone , and most of its other building methods need to explicitly pass the time zone, such as:

// build zoneddatetime based on instant and time zones  Public Static zoneddatetime ofinstant (Instant Instant, ZoneID zone) // according to Localdate, localtime and ZoneID structures  Public Static

Zoneddatetime can be converted directly to instant, for example:

Zoneddatetime Ldt == Ldt.toinstant ();

Format/Parse string

In Java 8, the main format class is Java.time.format.DateTimeFormatter, which is thread-safe and looks at an example:

DateTimeFormatter formatter = Datetimeformatter.ofpattern ("Yyyy-mm-dd HH:mm:ss"= Localdatetime.of ( 2016,8,18,14,20,45); System.out.println (Formatter.format (LDT));

The output is:

2016-08-18 14:20:45

To convert a string to a date and time object, you can use the parse method of the corresponding class, such as:

DateTimeFormatter formatter = Datetimeformatter.ofpattern ("Yyyy-mm-dd HH:mm:ss"= "2016-08-18 14:20:45"  = Localdatetime.parse (str, formatter);

Setting and modification times

There are two ways to modify the period and time, one is to set the absolute value directly, the other is to make relative additions and deletions on the basis of existing values, and most of Java 8 's classes support both, and as with Joda-time,most classes of Java 8 are immutable classes. The modification is done by creating and returning a new object, and the original object itself does not change.

Let's look at some examples.

Adjustment time is 3 o'clock in the afternoon 20

The code example is:

LocalDateTime Ldt == Ldt.withhour (All). Withminute (+). Withsecond (0). Withnano (0);

can also be:

LocalDateTime Ldt == Ldt.tolocaldate (). Attime (15, 20);

3 hours five minutes later

The sample code is:

LocalDateTime Ldt == ldt.plushours (3). Plusminutes (5);

LocalDateTime has many plusxxx and minusxxx methods for relative increases and decreases in time.

Today 0 O'Clock

Can be:

LocalDateTime Ldt == ldt.with (chronofield.milli_of_day, 0);      

Chronofield is an enumeration that defines a number of fields that represent the calendar, Milli_of_day represents the milliseconds in a day, values from 0 to (24 * 60 * 60 * 1,000)-1.

can also be:

LocalDateTime Ldt = Localdatetime.of (Localdate.now (), localtime.min);

Localtime.min means "00:00"

can also be:

LocalDateTime Ldt = Localdate.now (). Attime (0, 0);

Next Tuesday 10 o'clock in the morning full

Can be:

LocalDateTime Ldt == ldt.plusweeks (1). with (Chronofield.day_of_week, 2)    0). Withhour (10);

Next Tuesday 10 o'clock in the morning full

The next Tuesday is designated next week, if it is next Tuesday? This is related to the current week, if the current is Monday, then the next Tuesday is tomorrow, and the other case is next week, the code can be:

Localdate ld = localdate.now (); if (! Ld.getdayofweek (). Equals (Dayofweek.monday)) {    = ld.plusweeks (1= Ld.with (Chronofield.day_of_week, 2). Attime (10, 0);

For this complex tweak, Java 8 has a dedicated interface, Temporaladjuster, which is a functional interface defined as:

 Public Interface Temporaladjuster {    temporal adjustinto (temporal temporal);}

Temporal is an interface that represents a date or time object, Instant,localdatetime,localdate, and so on, and this interface is to adjust the date or time, there is a special class temporaladjusters, It provides a lot of temporaladjuster implementations, for example, for the next week's adjustment, by:

 Public Static Temporaladjuster Next (DayOfWeek DayOfWeek)

For the example above, the code can be:

Localdate ld == Ld.with (Temporaladjusters.next (Dayofweek.tuesday)). Attime (10, 0);

How is this next method implemented? Look at the code:

 Public Static Temporaladjuster Next (DayOfWeek DayOfWeek) {    int dowvalue = dayofweek.getvalue ();     return (temporal), {        int Caldow = temporal.get (day_of_week);         int Daysdiff = Caldow- dowvalue;         return temporal.plus (daysdiff >= 0 7-daysdiff:-Daysdiff, Days);}    ;}

It encapsulates some conditional judgments and specific adjustments within it, providing a more user-friendly interface.

There are many other methods in Temporaladjusters, some of which are as follows:

 public  static   Temporaladjuster firstdayofmonth ()  public  static   Temporaladjuster lastdayofmonth ()  public  static   Temporaladjuster firstinmonth (DayOfWeek DayOfWeek)  public  static   Temporaladjuster lastinmonth (DayOfWeek DayOfWeek)  public  static   Temporaladjuster previous (DayOfWeek DayOfWeek)  public  static  Temporaladjuster nextorsame (DayOfWeek DayOfWeek) 

These methods are more intuitive and do not explain that they are primarily packaged with some basic operations for date and time adjustments and are more user-friendly.

The last moment of tomorrow

The code can be:

LocalDateTime Ldt = Localdatetime.of (Localdate.now (). Plusdays (1), Localtime.max);

or for:

LocalDateTime Ldt = LocalTime.MAX.atDate (Localdate.now (). Plusdays (1));

Last last day of the month

The code can be:

LocalDateTime Ldt =  localdate.now ()        . With (Temporaladjusters.lastdayofmonth ())        . Attime ( Localtime.max);

How is Lastdayofmonth () implemented? Look at the code:

 Public Static Temporaladjuster Lastdayofmonth () {    return (temporal) , Temporal.with (Day_of_month, Temporal.range (Day_of_month). Getmaximum ());}        

Using the Range method, the maximum minimum value of the corresponding calendar unit can be obtained from its return value, and the last-minute code for the last day of the month can also be:

long maxdayofmonth ==  localdate.now ()        . Withdayofmonth ((int) Maxdayofmonth)        . Attime (Localtime.max);

The first Monday of the next month, 5 o'clock in the afternoon the whole

The code can be:

LocalDateTime Ldt = localdate.now ()        . Plusmonths (1)        . with (Temporaladjusters.firstinmonth ( Dayofweek.monday))        . Attime (

Calculation of the time period

Java 8 represents the time period of the class there are two, period and duration,period represents the difference between the date, with the month and day, can not represent the time, duration expressed the difference, with a stopwatch, etc., can also be expressed in days, a day strictly equal to 24 hours, Can not be expressed in years, see some examples below.

Calculates the difference between two dates

Look at an example of period:

Localdate ld1 = localdate.of (7, 3,+ = localdate.of) + "year"        + Period.getmonths () + "month" + period.getdays () + "Day");

The output is:

1 years March 18 days

Calculate age based on birthday

The sample code can be:

Localdate born = Localdate.of (1990,06,20); int year = Period.between (born, Localdate.now ()). Getyears ();

Calculate the number of minutes late

Suppose 9 o ' clock in the morning is work time, after 9 o ' clock is late, late to count the number of minutes late, how to calculate? Look at the code:

long lateminutes = Duration.between (        localtime.of (9,0),        

Conversions to Date/calendar objects

The Java 8 date and time API does not provide a way to convert the old Date/calendar to one another, but in practice we may be required, as described earlier, that date can be converted with instant through milliseconds, for other types, and also by milliseconds/ Instant convert each other.

For example, to convert LocalDateTime to date by the default time zone, the code can be:

 Public Static Date toDate (LocalDateTime ldt) {    returnnew  Date (Ldt.atzone (zoneid.systemdefault ())            . Toinstant (). Toepochmilli ());}

To convert Zoneddatetime to calendar, the code can be:

 Public Static Calendar Tocalendar (zoneddatetime zdt) {    = timezone.gettimezone (Zdt.getzone ());     = calendar.getinstance (TZ);    Calendar.settimeinmillis (Zdt.toinstant (). Toepochmilli ());     return Calendar;}

The calendar maintains the zoneddatetime time zone information.

To convert date to LocalDateTime in the default time zone, the code can be:

 Public Static LocalDateTime tolocaldatetime (date date) {    return  localdatetime.ofinstant (            Instant.ofepochmilli (Date.gettime ()),            Zoneid.systemdefault ());}

To convert the calendar to Zoneddatetime, the code can be:

 Public Static zoneddatetime tozoneddatetime (Calendar calendar) {    = zoneddatetime.ofinstant (            Instant.ofepochmilli (Calendar.gettimeinmillis ()),            Calendar.gettimezone (). Tozoneid ());     return ZDT;}

Summary

This section provides a brief introduction to the date and time APIs in Java 8, which introduces more classes than previous versions of date and calendar, but is clearer, more powerful and easier to use, and Java 8 learns many of the concepts and implementations of joda-time. Much like the joda-time we introduced earlier.

From section 91 to the discussion of lambda expressions to this section, we've covered the main content of Java 8.

At the same time, about the basic part of the entire Java programming, through a total of 95 sections of the content, we also basically discussed, the next section is the final article of this series, we have all 95 sections of the content of a brief comb.

(As with other chapters, all code in this section is located in Https://github.com/swiftma/program-logic, under package shuo.laoma.java8.c95)

----------------

To be continued, check out the latest articles, please pay attention to the public number "old Horse Programming" (Scan the QR code below), from the introduction to advanced, in layman's words, Lao Ma and you explore the nature of Java programming and computer technology. Original intentions, All rights reserved.

Thinking Logic of computer programs (8)-Date and time API for Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.