Java8 new Date API Localdate, localtime

Source: Internet
Author: User
Tags time zones

Objective

Due to the various problems of Java date, JAVA8 launched a new date API, very popular with a set of people.

Why do we need a new Java date/Time API?

Before we start studying the Java 8th/time API, let's take a look at why we need such a new API. In Java, there are many problems with existing date and time-related classes, including:

    • The definitions of the date/time classes in Java are inconsistent, with the date classes in both Java.util and java.sql packages, and the classes used for formatting and parsing are defined in the Java.text package.
    • Java.util.Date contains both a date and a time, and Java.sql.Date contains only dates, and it is not reasonable to include them in the java.sql package. The other two classes have the same name, which is a very bad design in itself.
      There are no explicitly defined classes for time, timestamp, formatting, and parsing. For the requirements of formatting and parsing, we have java.text.DateFormat abstract classes, but typically, the SimpleDateFormat class is used for such requirements.
    • All date classes are mutable, so they are not thread-safe, which is one of the biggest problems with the Java date class.
    • The date class does not provide internationalization, there is no time zone support, so Java introduces the Java.util.Calendar and Java.util.TimeZone classes, but they also have all of the above problems.

There are some other problems with the methods defined in the existing date and calendar classes, but the above questions are clear: Java requires a robust date/time class. This is also why Joda time plays an important role in the quality substitution of the Java date/times requirements.

Java 8th period/Time API

Java 8th/Time API is the implementation of JSR-310, its implementation goal is to overcome all the defects in the old date and time implementation, some design principles of the new date/Time API are:
Invariance: In the new date/Time API, all classes are immutable, which is good for multithreaded environments.
Separation of concerns: the new API explicitly separates human-readable datetime and Machine time (Unix timestamp), which defines different classes for date (date), Time, datetime, timestamp (Unix timestamp), and time zone.
Clarity: In all classes, methods are explicitly defined to accomplish the same behavior. For example, to get the current instance we can use the now () method, which defines the format () and the Parse () method in all classes, rather than having a separate class dedicated to it as before. To better handle the problem, all classes use Factory mode and policy mode, and once you use one of these classes, working with other classes is not difficult.
Practical operation: All new Date/Time API classes implement a series of methods to accomplish common tasks such as add, subtract, format, parse, extract individual parts from date/time, and so on.
Extensibility: The new Date/Time API is working on the ISO-8601 calendar system, but we can also apply it on non-iOS calendars.

Java Date/Time API pack

The Java Date/Time API contains the following corresponding packages.

    1. java.timePackage: This is the base package for the new Java Date/Time API, and all the main base classes are part of this package, such as: Localdate, LocalTime, LocalDateTime, Instant, Period, duration, and so on. All of these classes are immutable and thread-safe, and in the vast majority of cases, these classes are able to handle some of the public requirements effectively.
    2. java.time.chronoPackage: This package defines some generalization APIs for non-ISO calendar systems, and we can extend the Abstractchronology class to create our own calendar system.
      Java.time.format Package: This package contains classes that can format and parse date-time objects, and in most cases we should not use them directly, because the corresponding classes in the Java.time package already provide a way to format and parse.
    3. java.time.temporalPackage: This package contains some temporal objects that we can use to find a specific date or time on a date/time object, for example, to find the first or last day of a month. You can recognize these methods very easily, because they all have a "withxxx" format.
    4. java.time.zonePackage: This package contains classes that support different time zones and related rules.
Java Date/Time API sample

We have browsed the most important parts of the Java Date/time API and it is time to take a closer look at some of the most important classes by example.

    1. Java.time.LocalDate:LocalDate is an immutable class that represents the date of the default format (YYYY-MM-DD), and we can use the now () method to get the current time, or to provide the input year, The month and date input parameters to create a localdate instance. This class provides an overloaded method for the now () method, and we can pass in ZoneID to get the date of the specified time zone. This class provides the same functionality as Java.sql.Date, and for the use of this class, let's look at a simple example.
@Test Public void testlocaldate() {//current DateLocaldate today = Localdate. Now(); System. out.println("Current Date="+ today);//creating localdate by providing input argumentsLocaldate firstday_2014 = localdate. of( the, Month.January,1); System. out.println("Specific date="+ firstday_2014);//try Creating date by providing invalid inputs    //localdate feb29_2014 = Localdate.of (, month.february,);    //exception in thread "main" java.time.DateTimeException:    //invalid Date ' February ' as ' a leap year    //current date in "Asia/kolkata", you can get it from ZoneID JavadocLocaldate todaykolkata = localdate. Now(ZoneID. of("Asia/kolkata")); System. out.println("Current Date in ist="+ Todaykolkata);//java.time.zone.zonerulesexception:unknown time-zone id:ist    //localdate todayist = Localdate.now (Zoneid.of ("IST"));    //getting date from the base date i.e 01/01/1970Localdate datefrombase = localdate.Ofepochday(365); System. out.println("365th Day from base date="+ datefrombase); Localdate hundredDay2014 = localdate.Ofyearday( the, -); System. out.println("100th Day of 2014="+ hundredDay2014);}

Print

Current Date=2018-05-29Specific Date=2014-01-01Current Date in IST=2018-05-29365th day from base date= 1971-01-01100th day of 2014=2014-04-10
    1. Java.time.LocalTime:LocalTime is an immutable class whose instance represents a time in human readable format, with the default format hh:mm:ss.zzz. Like Localdate, this class also provides time zone support, as well as the ability to create instances of input parameters such as hours, minutes, and seconds, and we look at a simple program that demonstrates how the class is used.
@Test Public void Testlocaltime() {//current TimeLocalTime time = localtime. Now(); System. out.println("Current Time="+ time);//creating localtime by providing input argumentsLocalTime specifictime = localtime. of( A, -, -, +); System. out.println("Specific time of day="+ specifictime);//try creating time by providing invalid inputs    //localtime invalidtime = Localtime.of (25,20);    //exception in thread "main" java.time.DateTimeException:    //invalid value for hourofday (valid values 0-23):    //current date in "Asia/kolkata", you can get it from ZoneID JavadocLocalTime timekolkata = localtime. Now(ZoneID. of("Asia/kolkata")); System. out.println("Current time in ist="+ Timekolkata);//java.time.zone.zonerulesexception:unknown time-zone id:ist    //localtime todayist = Localtime.now (Zoneid.of ("IST"));    //getting date from the base date i.e 01/01/1970LocalTime specificsecondtime = localtime.Ofsecondofday(10000); System. out.println("10000th second Time="+ specificsecondtime);}

Print

Current Time=19:09:39.656Specific Time of Day=12:20:25.000000040Current Time in IST=16:39:39.65710000th second time= 02:46:40
    1. Java.time.LocalDateTime:LocalDateTime is an immutable date-time object that represents a set of date-time, the default format is yyyy-mm-dd-hh-mm-ss.zzz. It provides a factory method that receives localdate and localtime input parameters, creating LocalDateTime instances. Let's look at a simple example.
@Test Public void Testlocaldatetime() {//current DateLocalDateTime today = LocalDateTime. Now(); System. out.println("Current Datetime="+ today);//current Date using localdate and LocalTimeToday = LocalDateTime. of(Localdate. Now(), localtime. Now()); System. out.println("Current Datetime="+ today);//creating LocalDateTime by providing input argumentsLocalDateTime specificdate = LocalDateTime. of( the, Month.January,1,Ten,Ten, -); System. out.println("Specific date="+ specificdate);//try Creating date by providing invalid inputs    //localdatetime feb29_2014 = Localdatetime.of (month.february, 25,1,1);    //exception in thread "main" java.time.DateTimeException:    //invalid value for hourofday (valid values 0-23):    //current date in "Asia/kolkata", you can get it from ZoneID JavadocLocalDateTime todaykolkata = LocalDateTime. Now(ZoneID. of("Asia/kolkata")); System. out.println("Current Date in ist="+ Todaykolkata);//java.time.zone.zonerulesexception:unknown time-zone id:ist    //localdatetime todayist = Localdatetime.now (Zoneid.of ("IST"));    //getting date from the base date i.e 01/01/1970LocalDateTime datefrombase = LocalDateTime.Ofepochsecond(10000,0, Zoneoffset.UTC); System. out.println("10000th second time from 01/01/1970="+ datefrombase);}

In all these three examples, we have seen that if we provide invalid parameters to create date/time, then the system throws Java.time.DateTimeException, which is a runtime exception, and we do not need to capture it explicitly.
At the same time, we also see that the ability to get date/time data through the incoming ZoneID, you can get a list of supported ZoneID from its Javadoc, when running the above class, you can get the following output

Print

Current DateTime=2018-05-29T19:10:00.353Current DateTime=2018-05-29T19:10:00.353Specific Date=2014-01-01T10:10:30Current Date in IST=2018-05-29T16:40:00.35310000th second time from 01/01/1970= 1970-01-01T02:46:40
    1. The Java.time.Instant:Instant class is used in machine-readable time formats, which store datetime in the form of Unix timestamps, and we look at a simple program
 @Test   void  testtimestampforinstant  () {// Current timestamp  Instant timestamp = Instant. now     (); System. out . println     ( "current Timestamp ="  + Timestamp);    //instant from timestamp  Instant specifictime = Instant. ofepochmilli  (timestamp. toepochmilli     ()); System. out . println     ( "specific time ="  + specifictime);    //duration example  Duration thirtyday = Duration. ofdays     (30 ); System. out . println  (Thirtyday);}  
    1. Date API tools: As we mentioned earlier, most date/Time API classes implement a number of tool methods, such as: Add/Subtract days, weeks, months, and so on. There are other tool methods that can use Temporaladjuster to adjust dates and calculate periods for two days.
@Test Public void Testdatetool() {Localdate today = localdate. Now();//get the year, check if it's Leap yearSystem. out.println("Year"+ Today.GetYear() +"is the Leap year?"+ Today.Isleapyear());//compare localdate for before and afterSystem. out.println("Today is before 01/01/2015?"+ Today.Isbefore(Localdate. of( -,1,1)));//create LocalDateTime from LocaldateSystem. out.println("Current Time="+ Today.Attime(LocalTime. Now()));//plus and minus operationsSystem. out.println("Ten days after today would be"+ Today.plusdays(Ten)); System. out.println("3 weeks after today would be"+ Today.Plusweeks(3)); System. out.println("months after today would be"+ Today.plusmonths( -)); System. out.println("Ten days before today would be"+ Today.minusdays(Ten)); System. out.println("3 weeks before today would be"+ Today.Minusweeks(3)); System. out.println("months before today would be"+ Today.minusmonths( -));//temporal adjusters for adjusting the datesSystem. out.println("First date of this month="+ Today. with(Temporaladjusters.Firstdayofmonth())); Localdate lastdayofyear = today. with(Temporaladjusters.Lastdayofyear()); System. out.println("Last date of this year="+ lastdayofyear); Period Period = today.until(Lastdayofyear); System. out.println("Period format="+ period); System. out.println("Months remaining in the year="+ Period.getmonths());}
    1. Parsing and formatting: it is common to convert a date format to a different format, then parse a string and get a DateTime object. Let's take a look at a simple example.
@Test Public void Testformat() {//format ExamplesLocaldate date = Localdate. Now();//default FormatSystem. out.println("Default format of localdate="+ date);//specific FormatSystem. out.println(Date. Format(DateTimeFormatter.Ofpattern("D::mmm::uuuu"))); System. out.println(Date. Format(DateTimeFormatter.basic_iso_date)); LocalDateTime dateTime = LocalDateTime. Now();//default FormatSystem. out.println("Default format of Localdatetime="+ dateTime);//specific FormatSystem. out.println(DateTime. Format(DateTimeFormatter.Ofpattern("D::mmm::uuuu hh::mm::ss"))); System. out.println(DateTime. Format(DateTimeFormatter.basic_iso_date)); Instant timestamp = Instant. Now();//default FormatSystem. out.println("Default format of instant="+ timestamp);//parse ExamplesLocalDateTime dt = LocalDateTime.Parse("27:: May:: 21::39::48", DateTimeFormatter.Ofpattern("D::mmm::uuuu hh::mm::ss")); System. out.println("Default format after parsing ="+ dt);}
Reference

Original link: Journaldev translation: Importnew.com-justin Wu
Link: http://www.importnew.com/14140.html

Java8 new Date API Localdate, localtime

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.