Words Java Two sets of time tools were designed in a row , They are date type Date, And calendar type Calendar, Reasonably speaking, it is more than enough for coding development . However, as Java More and more widely used , People still find their disadvantages . Not to mention congenital defects Date type , Just talking about the rising star Calendar type , This calendar tool still has the following defects in actual development :
1、 When the calendar tool gets the current month , And Date All from 0 Start counting , Such as through get The value of January obtained by this method is 0;
2、 The calendar tool gets the day of the week , Sunday is at the top of the list , adopt get The Sunday value obtained by this method is 1, And on Monday it was 2!
3、 The minimum unit of time that a calendar tool can express is milliseconds , The time precision is not high enough , *** .
4、 Calendar tools don't provide a way to judge leap years .
5、 Calendar tools lack their own formatting tools , I have to rely on Date Formatting tools for types SimpleDateFormat, The date and time can be output as a string according to the specified format .
To make a long story short , Whether it's Date still Calendar, Coding is awkward when it comes to solving complex problems , So everyone Java The project basically needs to rewrite a date processing tool DateUtil, Encapsulate common date processing operations inside the new tool , Only in this way can we meet the development requirements of the actual business . therefore Date and Calendar Two brothers in need JDK1.1 Start fighting side by side , All the way to Java5、Java6 Even Java7, Later, I thought it was hopeless , Godfather Oracle in for a penny 、 Two endlessly , Finally in the Java8 New date and time types are introduced , The intention is to cure once and for all through the new type Date and Calendar A long standing disease .
The new date time type is not just a type , It's a family , Its members are mainly LocalDate、LocalTime、LocalDateTime wait , Next, we will introduce these date and time types :

1、 Local date type LocalDate
Getting an instance of a local date is simple , Call the now The method can , And as the name suggests, it gets the current date . Get the value of month, year and day from the local date , It's the habit number in daily life , For example, the corresponding value of January is 1, The corresponding value for December is 12, What's the value for Monday 1, What is the value for Sunday 7 wait . Besides , In addition, local date provides several common statistical methods , Include : How many days are there in the year of the date 、 How many days are there in the month of the date 、 Whether the year of the date is a leap year, etc . The following code shows an example of how to get various values from the local date :

 // Get an instance of the local date 
LocalDate date = LocalDate.now();
System.out.println("date=" + date.toString());
// Get the year of the date
int year = date.getYear();
System.out.println("year=" + year);
// Get the month of the date . Be careful getMonthValue Method returns a numeric month , and getMonth Method returns the month in English
int month = date.getMonthValue();
System.out.println("month=" + month + ", english month=" + date.getMonth());
// Get the date of the date
int dayOfMonth = date.getDayOfMonth();
System.out.println("dayOfMonth=" + dayOfMonth);
// Get the serial number of the date in a year
int dayOfYear = date.getDayOfYear();
System.out.println("dayOfYear=" + dayOfYear);
// What day of the week was the date obtained . Be careful getDayOfWeek Method returns the day of the week in English , trailing getValue Method to return the day of the week of the number
int dayOfWeek = date.getDayOfWeek().getValue();
System.out.println("dayOfWeek=" + dayOfWeek + ", english weekday=" + date.getDayOfWeek());
// How many days are there in the year in which the date is obtained
int lengthOfYear = date.lengthOfYear();
System.out.println("lengthOfYear=" + lengthOfYear);
// How many days are there in the month in which the date is obtained
int lengthOfMonth = date.lengthOfMonth();
System.out.println("lengthOfMonth=" + lengthOfMonth);
// Judge whether the year of the date is a leap year
boolean isLeapYear = date.isLeapYear();
System.out.println("isLeapYear=" + isLeapYear);

In addition to creating a local instance on the current date ,LocalDate It also supports the creation of local instances on specified dates , As the following code demonstrates :

 // Construct a date instance of the specified date 
LocalDate dateManual = LocalDate.of(2018, 11, 22);
System.out.println("dateManual=" + dateManual.toString());

As for the value for a unit ,LocalDate Special modification methods are also provided , For example plus A series of leading methods are used to increase the date value , With minus A series of leading methods are used to reduce date values , With with A series of leading methods are used to set the date value , The specific usage examples of these date modifications are as follows :

 dateManual = dateManual.plusYears(0); // Add several years 
dateManual = dateManual.plusMonths(0); // Add a few months
dateManual = dateManual.plusDays(0); // Add a few days
dateManual = dateManual.plusWeeks(0); // Add a few weeks
dateManual = dateManual.minusYears(0); // Decrease by several years
dateManual = dateManual.minusMonths(0); // Decrease by several months
dateManual = dateManual.minusDays(0); // Reduce the number of days
dateManual = dateManual.minusWeeks(0); // A few weeks less
dateManual = dateManual.withYear(2000); // Sets the specified year
dateManual = dateManual.withMonth(12); // Sets the specified month
dateManual = dateManual.withDayOfYear(1); // Set the date of the year
dateManual = dateManual.withDayOfMonth(1); // Set the day of the month

Besides , As a date type ,LocalDate As always, we support to judge the relationship between two date instances , such as equals Method to determine whether two dates are equal ,isBefore Method for judgment A Whether the date is B Before the date ,isAfter Method for judgment A Whether the date is B After the date, etc . The specific local date verification code is shown below :

 // Judge whether two dates are equal 
boolean equalsDate = date.equals(dateManual);
System.out.println("equalsDate=" + equalsDate);
// Judge A Whether the date is B Before the date
boolean isBeforeDate = date.isBefore(dateManual);
System.out.println("isBeforeDate=" + isBeforeDate);
// Judge A Whether the date is B After the date
boolean isAfterDate = date.isAfter(dateManual);
System.out.println("isAfterDate=" + isAfterDate);
// Judge A Is the date consistent with B Equal dates
boolean isEqualDate = date.isEqual(dateManual);
System.out.println("isEqualDate=" + isEqualDate);

2、 Local time type LocalTime
Previously introduced LocalDate You can only operate the date , If you want to operate in minutes and seconds, you need to pass the local time type LocalTime. The instance that gets the local time still calls the now Method , Then we can get the corresponding time, minute, second and even nanosecond through this instance ( One billionth of a second ), Here's how to call LocalTime Basic approach :

 // Get instance of local time 
LocalTime time = LocalTime.now();
System.out.println("time=" + time.toString());
// Get the clock where the time is
int hour = time.getHour();
System.out.println("hour=" + hour);
// Gets the minute that the time is in
int minute = time.getMinute();
System.out.println("minute=" + minute);
// Gets the second of the time
int second = time.getSecond();
System.out.println("second=" + second);
// Gets the nanosecond unit after the second of the time . One second is a thousand milliseconds , One millisecond is a thousand microseconds , One microsecond is a thousand nanoseconds , One second is a billion nanoseconds
int nano = time.getNano();
System.out.println("nano=" + nano);

Like local date LocalDate like that ,LocalTime It also allows the creation of time instances of specified time, minutes and seconds , It also supports modifying the clock independently 、 minute 、 Second and nanosecond . Of course, ways to change the time include plus Series method 、minus Series method 、with A series of methods and so on , An example of how they are called is as follows :

 // Construct a time instance of specified time, minute and second 
LocalTime timeManual = LocalTime.of(14, 30, 25);
System.out.println("timeManual=" + timeManual.toString());
timeManual = timeManual.plusHours(0); // Add several clocks
timeManual = timeManual.plusMinutes(0); // Add a few minutes
timeManual = timeManual.plusSeconds(0); // Add a few seconds
timeManual = timeManual.plusNanos(0); // Add a few nanoseconds
timeManual = timeManual.minusHours(0); // Reduce several clocks
timeManual = timeManual.minusMinutes(0); // A few minutes less
timeManual = timeManual.minusSeconds(0); // A few seconds less
timeManual = timeManual.minusNanos(0); // Reduce a few nanoseconds
timeManual = timeManual.withHour(0); // Sets the specified clock
timeManual = timeManual.withMinute(0); // Set the specified minutes
timeManual = timeManual.withSecond(0); // Sets the specified number of seconds
timeManual = timeManual.withNano(0); // Set the specified nanosecond

in addition ,LocalTime Still available equals、isBefore、isAfter And other methods are used to judge the sequence of two times , The specific method calls are as follows :

 // Judge whether two times are equal 
boolean equalsTime = time.equals(timeManual);
System.out.println("equalsTime=" + equalsTime);
// Judge A Whether the time is B Before time
boolean isBeforeTime = time.isBefore(timeManual);
System.out.println("isBeforeTime=" + isBeforeTime);
// Judge A Whether the time is B After time
boolean isAfterTime = time.isAfter(timeManual);
System.out.println("isAfterTime=" + isAfterTime);

3、 Local date time type LocalDateTime
There is now a LocalDate Special processing date , Have a LocalTime Special processing time, minute and second , You also need a type that can handle days, months, hours and seconds at the same time , It is the local date time type LocalDateTime.LocalDateTime It's basically equivalent to LocalDateTime And LocalTime A collection of , It has most of the methods of both , So I won't repeat it here . Here is the code snippet for creating an instance of this type , Readers can refer to the previous LocalDateTime And LocalTime Call code for , Try to make it up LocalDateTime Method call procedure for .

 // demonstration LocalDateTime Various methods of 
private static void showLocalDateTime() {
// Get an instance of the local date time
LocalDateTime datetime = LocalDateTime.now();
System.out.println("datetime=" + datetime.toString());
// LocalDateTime Approach is to LocalDate And LocalTime A collection of ,
// in other words LocalDate And LocalTime Most of the methods can be used directly LocalDateTime Use ,
// Therefore, it will not be shown below LocalDateTime How to call the detailed method of .
// Be careful LocalDateTime Does not provide lengthOfYear、lengthOfMonth、isLeapYear These three methods .
}

more Java For technical articles, see 《Java Development Notes ( order ) Chapter contents

Java Development Notes ( forty-three ) Better use of local date time for more related articles

  1. Java Development Notes ( 13、 ... and ) Compare sizes using relational operators

    In the front <Java Development Notes ( Nine ) Assignment operators and their evolution > I mentioned ,Java Equal sign in programming “=” Represents an assignment operation , It's not the mathematical meaning of equality .Java By equality symbol “==” The left and right sides are equal , The equal sign of corresponding mathematics “=”: ...

  2. Java Development Notes ( order ) Chapter contents

    Now the blog's Java The study articles are arranged into the following note catalogue , Convenient access . Chapter one First time to know JavaJava Development Notes ( One ) first Java Program Java Development Notes ( Two )Java Imperial division of Engineering Java Development Notes ( 3、 ... and )Java Imperial ...

  3. Java Development Notes ( eighty-three ) Checking null pointer with annotation technique

    Annotations are more advanced Java Development technology , The built-in annotations described earlier are dedicated to compiler checking code , Other annotations are defined and called by various frameworks , image Web Develop common Spring frame .Mybatis frame ,Android Develop common Butt ...

  4. Java Development Notes ( 23 ) Array tool Arrays

    Array as a data type of combination , It is necessary to provide some simple methods to deal with arrays , Include array comparison . Array copy . Array sorting and so on . So Java Specially designed Arrays Tools , The tool contains several common methods , It is convenient for programmer to process array ...

  5. Java Development Notes ( Forty-five ) Member properties and member methods

    A number of data types were described earlier , Except for basic types such as integers int. Double precision type double. Boolean type boolean outside , There are also some advanced, such as packaging integer Integer. String type String. Local date type LocalDate wait , that ...

  6. Java Development Notes ( 94 ) Performance advantages of file channels

    I introduced a bunch of concepts about byte caching , Maybe some friends have no time to digest , Although the use of the file channel is less than traditional I/O To simplify , However, there is a complicated byte cache , Clear and traditional I/O It's more complicated . Although byte caching enjoys the performance advantage of caching , but ...

  7. Java Development Notes ( Thirty-four ) Assignment and type conversion of string

    Whether it's basic char Character , Packing character type Character, They can only hold one character per variable , Can not meet the processing of a string of characters . In order to be able to operate a series of characters directly ,Java A special string type is designed String, This kind ...

  8. Java Development Notes ( Forty ) Conversion between date and string

    How to use the Date Tool to get each time value , But users prefer the shape “2018-11-24 23:04:18” The structure is clear . Concise string , Instead of reporting the description of each time unit and its value in turn . Since the date and time ...

  9. Java Development Notes ( Forty-two ) Common applications of calendar tools

    The calendar tool was described earlier Calendar The basic usage of , At first glance Calendar And Date Two is half the weight , It doesn't seem to make much difference , So why bother with a new thing ? Obviously, I underestimated it Calendar, In fact, it plays an important role , Pick up ...

Random recommendation

  1. centos6.x Power on stuck

    Problem description : centos6.x Boot stuck at the progress bar Remote login , Check the system log , Look where the card is By remote connection ,tail -fn 20 /var/log/messages Found an error : init: prefdm ...

  2. DragSelectRecyclerView Long press to slide multiple images android Special effects

    High imitation Google Photo album multi selection effect , Long press a item Then slide the selection to any item, Very good results , It is suitable for the effect of multiple selection of album pages . This example is mainly about customization DragSelectRecyclerView As shown below gridv ...

  3. VIM Common error resolution

    1.option ‘omnifunc’ is not set error : vim7 Next Omni completion It is not enabled by default , Sometimes it's custom vimrc The files will be filled automatically , for example vim-autoc ...

  4. Simplicity ES6 - class

    Preface With ES6 Finalization of standards , Many of the features tend to be stable , Major browsers are also gradually implementing these features , So right. ES6 There's nothing wrong with knowing more . Get ready I'm learning ES6 Before , We need an environment to test ES6 Code . I recommend using n ...

  5. DS18B20 Thermometry

    The project needs to implement distributed large-scale temperature measurement , need 52 A temperature measuring point , sampling DS18B20 Design . 30cm One point , altogether 8 Two points in series . Adopt national standard single core single strand copper wire BV0.5 Make wires , The test is normal for a while , It's not normal for a while . The line changed in the back , The test is ...

  6. [Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds...

    INSERT INTO `ftms_active_dealer`(dealer_code,dealer_name,active_id,dealer_state)VALUES('415A1',' He Lei '1 ...

  7. AIX stack_hard Parameters

    OS:AIX 7.1 root.oracle.grid Users view resource restrictions , among stack be limited to , Need to be in /etc/security/limits add stack_hard = -1, Subject to hard limits ! [ora ...

  8. SVN Migrate to GitLab, Keep submission records

    1. download GitBash This tool comes with it git svn command , No need to download git-svn Tools 2.GitBash Enter the following command in the terminal git svn clone svnurl srcPath 3.push Local repository ...

  9. MyISAM And InnoDB Distinction and choice between the two , Detailed summary , Performance comparison

    1.MyISAM: Default table type , It's based on the tradition of ISAM type ,ISAM yes Indexed Sequential Access Method ( Indexed sequential access methods ) Abbreviation , It's the standard way to store records and files . No ...

  10. shell command

    View network card traffic report  sar  -n  DEV  kill pid  ps  -ef  |grep xxx  |grep -v grep  |awk '{print $2}'   |xargs   ki ...