Java8 practical tips for date and time

Source: Internet
Author: User

The new Date API
    • ZoneID: Time zone ID, which determines the rules that instant and localdatetime convert to each other
    • Instant: Used to represent a point on the timeline
    • Localdate: Represents a date without a time zone, Localdate is immutable and thread-safe
    • LocalTime: Indicates time without a time zone, localtime is immutable and thread-safe
    • LocalDateTime: Represents a datetime with no time zone, LocalDateTime is immutable and thread-safe
    • Clock: Used to access the current time, date, time, timezone
    • Duration: The number of times in seconds and nanoseconds

The most common is localdate, localtime, LocalDateTime, from their names can be seen in the operation of the date and time.

These classes are primarily used in contexts where the current zone does not need to be explicitly specified. In this section we will discuss the most commonly used APIs.

Localdate

Localdate represents the date of an iOS format (YYYY-MM-DD) and can store dates such as birthdays, anniversaries, and so on.
Get the current date:

Localdate localdate = localdate.now (); System.out.println ("localdate:" + localdate);

Output

Localdate can specify a specific date, call the of or Parse method to return the instance:

Localdate.of (2017, 07, 27); Localdate.parse ("2017-07-27");

Of course there are some other ways that we can take a look at:

// add a day for today, that is to get tomorrow  = Localdate.now (). Plusdays (1); // minus one months from today .  = Localdate.now (). Minus (1, chronounit.months);

Output

Here are two examples to parse the date 2017-07-27to get the week of the week and the day of the month:

DayOfWeek Thursday = Localdate.parse ("2017-07-27"). GetDayOfWeek (); System.out.println ("Thursday:" + Thursday); int twenty = Localdate.parse ("2017-07-27"). GetDayOfMonth (); System.out.println ("Twenty:" + twenty);

Output

Try this year is not leap years:

boolean leapyear = localdate.now (). Isleapyear (); System.out.println ("Whether leap year:" + leapyear);

Output

Determine whether before or after a date:

boolean notbefore = Localdate.parse ("2017-07-27")                . Isbefore (Localdate.parse ("2017-07-29") )); System.out.println ("Notbefore:" + notbefore); boolean isafter = Localdate.parse ("2017-07-27"). Isafter (Localdate.parse ("2017-07-29")); System.out.println ("isafter:" + isafter);

Output

Get the first day of the month:

Localdate firstdayofmonth = Localdate.parse ("2017-07-27")                . With (Temporaladjusters.firstdayofmonth ()); System.out.println ("The first day of this month:"+ = firstdayofmonth.withdayofmonth (1); System.out.println ("The first day of this month:" + firstdayofmonth);

Output

Judging if today is my birthday, for example, my birthday is 2017-07-27

localdate birthday = Localdate.of (,)== monthday.from (Localdate.now ()); System.out.println ("Whether today is my birthday:" + today.equals (BIRTHDAYMD));

Output

LocalTime

LocalTime represents a time, not a date, and here's how it's used.

Get the time now

LocalTime now = Localtime.now (); System.out.println ("Present time:" + now);

Output

Resolves a string time to localtime

LocalTime nowtime = Localtime.parse ("14:18"); System.out.println ("Time is:" + nowtime);

Output

Create a time using static method

LocalTime Nowtime = localtime.of (+); System.out.println ("Time is:" + nowtime);

Use parse string and add an hour

LocalTime Nexthour = Localtime.parse ("14:18"). Plus (1, chronounit.hours); System.out.println ("Next one Hours:" + nexthour);

Output

Get hours, minutes of time

int hour = localtime.parse ("14:18"). Gethour (); System.out.println ("Hours:" + hour); int minute = Localtime.parse ("14:18"). Getminute (); System.out.println ("minutes:" + minute);

Output

We can also check whether a time is before or after another time through a similar API.

boolean isbefore = Localtime.parse ("14:18"). Isbefore (Localtime.parse ("15:18")); boolean isafter = Localtime.parse ("14:18"). Isafter (Localtime.parse ("15:18")); System.out.println ("Isbefore:" + Isbefore); System.out.println ("isafter:" + isafter);

Output

The start and end of each day are also used as constants in the LocalTime class for our use:

System.out.println (Localtime.max); System.out.println (localtime.min);

Output:

LocalDateTime

LocalDateTime is used to represent a date and time, which is one of the most commonly used classes.

Get the current date and time:

LocalDateTime now = Localdatetime.now (); System.out.println ("present:" + now);

Output

The following uses static methods and strings to create LocalDateTime objects separately

LocalDateTime. Now ();
Localdatetime.of (month.july, +); Localdatetime.parse ("2017-07-20t15:18:00"); // at the same time, ' LocalDateTime ' also provides APIs to add or subtract dates and times: LocalDateTime tomorrow = now.plusdays (1); System.out.println ("This Time of Tomorrow:" += now.minushours (2); System.out.println ("Two hours ago:" + minustowhour);

Output

This class also provides a series of get methods to get specific units:

LocalDateTime. Now ();
Month month = now.getmonth (); System.out.println ("Current month:" + month);

Output

Date formatting

In the daily development we use the most perhaps is the date, the time format, that in the Java8 kind of how to operate

LocalDateTime now == Datetimeformatter.ofpattern ("Yyyy-mm-dd HH:mm:ss"); System.out.println ("default format:" + now ); System.out.println ("Custom format:" += Localdatetime.parse ("2017-07-27 14:53:40", DateTimeFormatter); System.out.println ("string to LocalDateTime:" + localDateTime);

Output

You can also format the date and time as a string using the Format method of DateTimeFormatter

DateTimeFormatter DateTimeFormatter = Datetimeformatter.ofpattern ("yyyy-mm-dd"=  Datetimeformatter.format (Localdate.now ()); System.out.println ("date to String:" + datestring);

Output

Date Period

The Period class is used to modify the difference between a given date or two dates obtained.

Add 5 days to the initialized date:

Localdate initialdate = Localdate.parse ("2017-07-27"); Localdate finaldate   = Initialdate.plus (period.ofdays (5)); System.out.println ("Date of initialization:" + initialdate); System.out.println ("Plus date:" + finaldate);

The cycle API provides us with a comparison of two dates, as follows to get the difference in days:
Long between = ChronoUnit.DAYS.between (initialdate, finaldate); System.out.println ("Gap days:" + between);

The above code will return 5, and of course you want to get two different dates for how many hours is also simple.

Output

Conversion with legacy code

In the previous code you might have a large number of date classes, and how to convert it to a Java8 type of time class

Date and Instant convert each other

Date Date == Date.toinstant ();

Date conversion to LocalDateTime

LocalDateTime LocalDateTime = Localdatetime.from (new  Date ()); System.out.println (localDateTime);

LocalDateTime turn Date

Date date = Date.from (Localdatetime.atzone (Zoneid.systemdefault ()). Toinstant ());

localdate turn Date

Date date = Date.from (Localdate.now (). Atstartofday (). Atzone (Zoneid.systemdefault ()). Toinstant ());

Java8 practical tips for date and time

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.