Java 8– Date and time practical tips

Source: Internet
Author: User
Tags parse string

When you start using Java to manipulate dates and times, there are some tricky things to do. You may return the number of milliseconds from January 1, 1970 to today by System.currenttimemillis (). Or you can use the date class to manipulate dates, and you need to use the Calendar class when you're experiencing the plus and minus months and days, and you need the Java.text.DateFormat class when you need to format the date. All in all, working with dates in Java is not so convenient that many developers have to use third-party libraries, such as: Joda-time.

Problems with existing APIs
    • Thread Safety: Date and calendar are not thread-safe, you need to write extra code to handle thread safety issues
    • API design and ease of use: because date and calendar are poorly designed, you can't do your day-to-date operations
    • Zoneddate and time: You have to write extra logic to handle the timezone and those old logic

Fortunately, in the JSR 310 specification, a new API has been added to Java8, and in the Java.time package, the new API corrects past flaws,

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:

12 LocalDate localDate = LocalDate.now();System.out.println("localDate: "+ localDate);
1 localDate: 2017-07-20

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

12 LocalDate.of(2017, 07, 20);LocalDate.parse("2017-07-20");

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

Add a day for today, that is to get tomorrow

1 LocalDate tomorrow = LocalDate.now().plusDays(1);

Minus one months from today.

1 LocalDate prevMonth = LocalDate.now().minus(1, ChronoUnit.MONTHS);

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

1234 DayOfWeek thursday = LocalDate.parse("2017-07-20").getDayOfWeek();System.out.println("周四: "+ thursday);int twenty = LocalDate.parse("2017-07-20").getDayOfMonth();System.out.println("twenty: "+ twenty);

Try this year is not leap years:

12 booleanleapYear = LocalDate.now().isLeapYear();System.out.println("是否闰年: "+ leapYear);

Determine whether before or after a date:

12345 boolean notBefore = LocalDate.parse("2017-07-20")                .isBefore(LocalDate.parse("2017-07-22"));System.out.println("notBefore: " + notBefore);boolean isAfter = LocalDate.parse("2017-07-20").isAfter(LocalDate.parse("2017-07-22"));System.out.println("isAfter: " + isAfter);

Get the first day of the month:

12345 localdate firstdayofmonth = Localdate.parse ( )                   .with ( Temporaladjusters.firstdayofmonth ()); system.out.println ( "first day of the month:" + firstdayofmonth); firstdayofmonth = Firstdayofmonth.withdayofmonth ( 1 system.out.println ( "first day of the month:" + firstdayofmonth);

Judging whether today is my birthday, for example, my birthday is 2009-07-20

1234 LocalDate birthday = LocalDate.of(2009, 07, 20);MonthDay birthdayMd = MonthDay.of(birthday.getMonth(), birthday.getDayOfMonth());MonthDay today = MonthDay.from(LocalDate.now());System.out.println("今天是否是我的生日: "+ today.equals(birthdayMd));
LocalTime

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

Get the current time, output 15:01:22.144

12 LocalTime now = LocalTime.now();System.out.println("现在的时间: "+ now);

Resolves a string time to localtime, output 15:02

12 LocalTime nowTime = LocalTime.parse("15:02");System.out.println("时间是: "+ nowTime);

Create a time using static method

12 LocalTime nowTime = LocalTime.of(15, 02);System.out.println("时间是: "+ nowTime);

Use parse string and add an hour, output 16:02

12 LocalTime nextHour = LocalTime.parse("15:02").plus(1, ChronoUnit.HOURS);System.out.println("下一个小时: "+ nextHour);

Get hours, minutes of time

1234 inthour = LocalTime.parse("15:02").getHour();System.out.println("小时: " + hour);int minute = LocalTime.parse("15:02").getMinute();System.out.println("分钟: "+ minute);

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

1234 boolean isbefore = Localtime.parse ( " 15:02 " " 16:02 " boolean isafter = Localtime.parse ( "). Isafter (Localtime.parse ( system.out.println ( "Isbefore:" + Isbefore); system.out.println ( "Isafter:" + isafter);

Output Isbefore:true, Isafter:false.

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

12 System.out.println(LocalTime.MAX);System.out.println(LocalTime.MIN);

Output:

12 23:59:59.99999999900:00

LocalTime that's all, let's take a look at LocalDateTime

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:

12 LocalDateTime now = LocalDateTime.now();System.out.println("现在: "+ now);

Output

1 现在: 2017-07-20T15:17:19.926

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

123456789 LocalDateTime.of(2017, Month.JULY, 20, 15, 18);LocalDateTime.parse("2017-07-20T15:18:00"); //同时`LocalDateTime`也提供了相关API来对日期和时间进行增减操作: LocalDateTime tomorrow = now.plusDays(1);System.out.println("明天的这个时间: " + tomorrow);LocalDateTime minusTowHour = now.minusHours(2);System.out.println("两小时前: " + minusTowHour);

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

12 Month month = now.getMonth();System.out.println("当前月份: "+ month);
Date formatting

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

123456 localdatetime now = Localdatet Ime.now (); datetimeformatter datetimeformatter = Datetimeformatter.ofpattern ( " Yyyy-mm-dd HH:mm:ss " ); system.out.println ( "default formatting:" + now); system.out.println ( + Now.format (DateTimeFormatter)); localdatetime LocalDateTime = Localdatetime.parse ( " 2017-07-20 15:27:44 " system.out.println ( + localDateTime);

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

123 DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");String dateString = dateTimeFormatter.format(LocalDate.now());System.out.println("日期转字符串: "+ dateString);
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:

1234 LocalDate initialDate = LocalDate.parse("2017-07-20");LocalDate finalDate = initialDate.plus(Period.ofDays(5));System.out.println("初始化日期: "+ initialDate);System.out.println("加日期之后: "+ finalDate);

The cycle API provides us with a comparison of two dates, as follows to get the difference in days:

12 longbetween = ChronoUnit.DAYS.between(initialDate, finalDate);System.out.println("差距天数: "+ between);

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

Conversion with legacy code

You might have a lot of date classes in the previous code, how do you convert it to a Java8 time class?

Date and instant convert each other

12 Date date = Date.from(Instant.now());Instant instant = date.toInstant();

Date conversion to LocalDateTime

12 LocalDateTime localDateTime = LocalDateTime.from(newDate());System.out.println(localDateTime);

LocalDateTime Turn Date

12 Date date =Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

Localdate Turn Date

12 Date date =Date.from(LocalDate.now().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()

Java 8– Date and time practical tips

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.