Get the date in Java 8

Source: Internet
Author: User
Tags time zones

Objective

The previous article wrote "How is SimpleDateFormat safe to use?" , which describes how SimpleDateFormat handles date/time, and how to ensure thread safety, and describes the DateTimeFormatter class, which is the default thread-safe for processing time/date in Java 8. So how do you deal with some of the most common dates/times in your life in Java 8? For example: Calculate a date after one week, calculate a date a year ago or a year later, check for leap years, and so on.

Next, 20 task-based instances are created to learn the new features of Java 8. Start with the date of the simplest creation day, then create a time zone, and then simulate a task in a date reminder app--Calculate the expiration days for important dates, such as birthdays, anniversaries, billing days, premiums due dates, credit card expiry dates, and so on.

Example 1, getting today's date in Java 8

Localdate in Java 8 is used to represent today's date. Unlike Java.util.Date, it has only dates and no time. Use this class when you only need to represent a date.

1LocalDate now = LocalDate.now();
2System.out.println(now);

The result is:

12018-06-20

The above code creates the date of the day without the time information. The printed date format is very friendly and does not print out a bunch of unformatted information like the old date class.

Example 2, getting the year, month, and day information in Java 8

The Localdate class provides a quick way to get the year, month, and day, and its instances contain many other date attributes. By invoking these methods, it is convenient to get the date information you need, without having to rely on the Java.util.Calendar class as before.

1LocalDate now = LocalDate.now();
2int year = now.getYear();
3int monthValue = now.getMonthValue();
4int dayOfMonth = now.getDayOfMonth();
5System.out.printf("year = %d, month = %d, day = %d", year, monthValue, dayOfMonth);

The result is:

1year = 2018, month = 6, day = 20
Example 3, working with a specific date in Java 8

In the first example, we created the day date very easily by using the static Factory method now (), and you can call another useful factory method Localdate.of () to create any date, which requires passing in the year, month, and day parameters to return the corresponding Localdate instance. The advantage of this method is that the design error of the old API is not repeated, such as the year starting at 1900, the month starting from 0 and so on. The date is WYSIWYG, as shown in the following example, June 20, without any hidden organs.

1LocalDate date = LocalDate.of(2018, 06, 20);
2System.out.println(date);

You can see that the created date is exactly as expected, exactly as it was written June 20, 2018.

Example 4, determining whether two dates are equal in Java 8

A class of time in real life is to determine whether two dates are equal. You will often check that today is not a special day, such as birthdays, anniversaries or non-trading days. You need to compare the specified date with a specific date, for example, to determine whether the day is a holiday. The following example will help you in the way of Java 8 to solve, you must have thought, localdate overloaded the equal method, see the following example:

1LocalDate now = LocalDate.now();
2LocalDate date = LocalDate.of(2018, 06, 20);
3if (date.equals(now)) {
4    System.out.println("同一天");
5}

In this example we compare the same two dates. Note that if the date of the comparison is of character type, it needs to be parsed into a date object before being judged.

Example 5, checking for recurring events like birthdays in Java 8

Another datetime in Java is the process of checking for recurring events such as monthly bills, wedding anniversaries, EMI days, or insurance payment days. If you work on an e-commerce site, there must be a module to send greeting messages to customers on Christmas and Thanksgiving holidays. How do you check these festivals or other recurring events in Java? The answer is the MonthDay class. This class combines the month and day, minus the year, which means that you can use it to judge the events that occur every year. Similar to this class, there is a Yearmonth class. These classes are also immutable and thread-safe value types. Below we examine the recurring events through MonthDay:

1LocalDate now = LocalDate.now();
2LocalDate dateOfBirth = LocalDate.of(2018, 06, 20);
3MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
4MonthDay currentMonthDay = MonthDay.from(now);
5if (currentMonthDay.equals(birthday)) {
6    System.out.println("Happy Birthday");
7} else {
8    System.out.println("Sorry, today is not your birthday");
9}

Result: (note: Getting the current time may not be the same as when you look at it, so the result may not be the same as when you look at it)

1Happy Birthday

As long as the day's date and birthday match, no matter which year will print out the congratulations message. You can integrate the program into the system clock to see if your birthday is being alerted, or write a unit test to check that your code is running correctly.

Example 6, getting the current time in Java 8

Like the Java 8 Get date example, the acquisition time is using the LocalTime class, a localdate close relative who has only time without dates. You can call the static factory method now () to get the current time. The default format is hh:mm:ss:nnn.

1LocalTime localTime = LocalTime.now();
2System.out.println(localTime);

Results:

113:35:56.155

You can see that the current time contains only time information and no date.

Example 7, how to add an hour to an existing time

It is common to calculate the future time by adding hours, minutes, seconds. Java 8, in addition to the invariant type and thread-safe benefits, provides a better plushours () method to replace add () and is compatible. Note that these methods return a completely new localtime instance, and because of its immutability, it is important to assign a value to the variable after it returns.

1LocalTime localTime = LocalTime.now();
2System.out.println(localTime);
3LocalTime localTime1 = localTime.plusHours(2);//增加2小时
4System.out.println(localTime1);

Results:

113:41:20.721
215:41:20.721

As you can see, the new time is increased by 2 hours on the basis of the current time 13:41:20.721.

Example 8, how to calculate the date after one week

Similar to the last example calculated two hours later, this example calculates the date one week later. The localdate date does not contain time information, and its plus () method is used to increase days, weeks, and months, and the Chronounit class declares these units of time. Since Localdate is also invariant, be sure to assign a value to the variable after returning.

1LocalDate now = LocalDate.now();
2LocalDate plusDate = now.plus(1, ChronoUnit.WEEKS);
3System.out.println(now);
4System.out.println(plusDate);

Results:

12018-06-20
22018-06-27

You can see that the new date is 7 days from today, that is, a week. You can add 1 months, 1 years, 1 hours, 1 minutes, or even a century in the same way, more options to view the Chronounit class in the Java 8 API.

Example 9, calculating a date a year ago or a year later

Continuing with the example above, we used the Localdate Plus () method to increase the number of days, weeks, or months in the previous example, and we use the minus () method to calculate the date a year ago.

1LocalDate now = LocalDate.now();
2LocalDate minusDate = now.minus(1, ChronoUnit.YEARS);
3LocalDate plusDate1 = now.plus(1, ChronoUnit.YEARS);
4System.out.println(minusDate);
5System.out.println(plusDate1);

Results:

12017-06-20
22019-06-20
Example 10, clock clock class using Java 8

Java 8 adds one clock clock class to get the timestamp at the time, or the datetime information in the current time zone. The previous use of System.currenttimeinmillis () and Timezone.getdefault () can be replaced by Clock.

1Clock clock = Clock.systemUTC();
2Clock clock1 = Clock.systemDefaultZone();
3System.out.println(clock);
4System.out.println(clock1);

Results:

1SystemClock[Z]
2SystemClock[Asia/Shanghai]
Example 11, how to use Java to determine whether a date is earlier than or later than another date

Another common operation is how to tell if a given date is greater than one day or less than one day? In Java 8, the Localdate class has two classes of methods Isbefore () and Isafter () for comparing dates. Returns true if the given date is less than the current date when the Isbefore () method is called.

1 LocalDate tomorrow = LocalDate.of(2018,6,20);
2 if(tomorrow.isAfter(now)){
3     System.out.println("Tomorrow comes after today");
4 }
5 LocalDate yesterday = now.minus(1, ChronoUnit.DAYS);
6 if(yesterday.isBefore(now)){
7     System.out.println("Yesterday is day before today");
8 }

It is convenient to compare dates in Java 8 without the need for additional Calendar classes to do the basic work.

Example 12, working with time zones in Java 8

Java 8 not only separates the date and time, but also separates the time zone. There are now a series of separate classes such as ZoneID to handle a specific time zone, Zonedatetime class to represent time in a time zone. This was done by the GregorianCalendar class before Java 8.

1ZoneId america = ZoneId.of("America/New_York");
2LocalDateTime localtDateAndTime = LocalDateTime.now();
3ZonedDateTime dateAndTimeInNewYork  = ZonedDateTime.of(localtDateAndTime, america );
4System.out.println(dateAndTimeInNewYork);
Example 13, how to indicate a fixed date such as credit card expiry, the answer is Yearmonth

Similar to the example of monthday checking for duplicate events, Yearmonth is another combination class that represents the credit card expiry date, FD expiry date, futures option expiry date, and so on. You can also use this class to get the number of days in a month, the Lengthofmonth () method of the Yearmonth instance can return the number of days of the month, which is useful when judging whether there are 28 or 29 days in February.

1YearMonth currentYearMonth = YearMonth.now();
2System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
3YearMonth creditCardExpiry = YearMonth.of(2018, Month.FEBRUARY);
4System.out.printf("Your credit card expires on %s %n", creditCardExpiry);

Results:

1Days in month year 2018-06: 30
2Your credit card expires on 2018-02
Example 14, how to check a leap year in Java 8

The Localdate class has a very useful method isleapyear () to determine whether the instance is a leap year.

Example 15, calculating the number of days and months between two dates

One common date operation is to calculate the number of days, weeks, or months between two dates. In Java 8, you can use the Java.time.Period class to do the calculations. In the following example, we calculate the number of months between the day and the Future Day.

1LocalDate date = LocalDate.of(2019, Month.MARCH, 20);
2Period period = Period.between(now, date);
3System.out.println("离下个时间还有" + period.getMonths() + " 个月");
Example 16, date and time with slack information

In Java 8, the Zoneoffset class is used to represent time zones, for example, if India differs from the GMT or UTC Standard Time zone +05:30, the corresponding time zone can be obtained through the Zoneoffset.of () static method. Once you get the time difference, you can create a Offsetdatetime object by passing in LocalDateTime and Zoneoffset.

1LocalDateTime datetime = LocalDateTime.of(2014, Month.JANUARY, 14,19,30);
2ZoneOffset offset = ZoneOffset.of("+05:30");
3OffsetDateTime date = OffsetDateTime.of(datetime, offset);  
4System.out.println("Date and Time with timezone offset in Java : " + date);
Example 17, getting the current timestamp in Java 8

If you remember how the current timestamp was obtained before Java 8, you are finally relieved. The Instant class has a static factory method now () that returns the current timestamp as follows:

1Instant timestamp = Instant.now();
2System.out.println(timestamp);

Results:

12018-06-20T06:35:24.881Z

The timestamp information contains both the date and time, which is much like the java.util.Date. In fact, the Instant class is indeed equivalent to the date class before Java 8, and you can use the date class and the Instant class to convert each other, for example: Date.from (Instant) converts Instant to Java.util.date,d Ate.toinstant () converts the Date class to the Instant class.

Example 18, how to use the predefined formatting tools in Java 8 to parse or format dates

In the world before Java 8, the formatting of dates and times is very strange, the only helper class SimpleDateFormat is also non-thread-safe, and used as a local variable parsing and formatting dates is cumbersome. Fortunately, thread-local variables make it usable in a multithreaded environment, but this is the past. Java 8 introduces a new date-time format tool that is thread-safe and easy to use. It comes with some of the most common built-in formatting tools.

See my previous article, "How is simpledateformat safe to use?" 》

Example 19, how to resolve dates in Java using a custom formatting tool

Although the built-in formatting tools are useful, sometimes you need to define a specific date format. You can call DateTimeFormatter's Ofpattern () static method and pass in any format to return the example, the characters in the format are the same as the previously represented, M for the month, and M for the minute. A Datetimeparseexception exception is thrown if the format is not canonical, but a logic error such as M is not thrown out of the ordinary.

See my previous article, "How is simpledateformat safe to use?" 》

Example 20, how to convert a date to a string in Java 8

The

on two is primarily a parse date from a string. Now we turn to convert the LocalDateTime date instance into a string of a specific format. This is by far the simplest way to date Java dates to strings. The following example returns a formatted string representing the date. Similar to the previous one, you need to create a DateTimeFormatter instance and pass in the format, but this callback calls the format () method, not the parse () method. This method converts the incoming date into a string of the specified format.

1LocalDateTime arrivalDate  = LocalDateTime.now();
2try {
3    DateTimeFormatter format = DateTimeFormatter.ofPattern("MMMdd yyyy  hh:mm a");
4    String landing = arrivalDate.format(format);
5    System.out.printf("Arriving at :  %s %n", landing);
6}catch (DateTimeException ex) {
7    System.out.printf("%s can‘t be formatted!%n", arrivalDate);
8    ex.printStackTrace();
9}
The focus of the Java 8th time API

With these examples, you must have mastered the new knowledge points of the Java 8th time API. Now let's review the use points of this elegant API:

1) provides javax.time.ZoneId to get the time zone.

2) Localdate and LocalTime classes are available.

3) All date and time APIs in Java 8 are immutable and thread-safe, while Java.util.Date and SimpleDateFormat in the existing date and Calendar APIs are non-thread safe.

4) The main package is Java.time, which contains some classes that represent the date, time, and time interval. There are two sub-packages Java.time.format for formatting, java.time.temporal for the lower-level operation.

5) The time zone represents the standard time that is commonly used in an area on Earth. Each time zone has a code name, which usually consists of a region/city composition (Asia/tokyo), plus a difference in Greenwich or UTC. For example, Tokyo's time difference is +09:00.

6) The Offsetdatetime class actually combines the LocalDateTime class and the Zoneoffset class. Used to represent the full date (year, month, day) and time (hour, minute, second, nanosecond) information that contains the Greenwich or UTC difference.

7) The DateTimeFormatter class is used for formatting and parsing time. Unlike SimpleDateFormat, this class is immutable and thread-safe, and you can assign values to static constants when needed. The DateTimeFormatter class provides a number of built-in formatting tools and also allows you to customize. Parse () is also provided in the transformation to parse the string into a date, and if parsing is an error, it throws datetimeparseexception. The DateTimeFormatter class also has format () for formatting dates and throws a Datetimeexception exception if an error occurs.

8) Add a little, date format "MMM d yyyy" and "MMM dd yyyy" have some subtle differences, the first format can parse "Jan 2 2014" and "Jan 14 2014", while the second in parsing "Jan 2 2014" will throw an exception, The requirement date in the second format must be two bits. If you want to fix it, you must make 0 in front of the date with only one digit, meaning "Jan 2 2014" should be written as "Jan 02 2014".

Related articles

Get the date in Java 8

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.