Java8 the use of time-processing classes (Localdate ... )

Source: Internet
Author: User

With it, who is still using date? Calendar?

In fact, it can not be so absolute, after all, not to that extent. JAVA8 new processing time of a group of classes (Localdate, LocalDateTime, localtime), just started to feel very laborious, no calendar useful, but really used to think it is more useful ah. We recommend that you use it later. Talk less, look at the code ~

1, date and localdate of the mutual transfer

Date Turn localdate:

New= Date.toinstant (). Atzone (Zoneid.systemdefault ()). Tolocaldate ();

Localdate Turn Date:

LocalDateTime LocalDateTime == Date.from (Localdatetime.toinstant (ZONEOFFSET.UTC))

Obviously, a instant is used between localdate and date to convert the type, or it can be converted in other ways. Localdate.of () and so on, a little more complex ruthless!

2, localdate some time operation

1DateTimeFormatter ymd = Datetimeformatter.ofpattern ("Yyyy-mm-dd");2 //string converted to Localdate type3Localdate ld = Localdate.parse ("2015-11-23", YMD);4SYSTEM.OUT.PRINTLN ("Month Day:" +ld.getyear () + "-" +ld.getmonthvalue () + "-" +ld.getdayofmonth ());5SYSTEM.OUOT.PRINTLN ("Total days starting January 1, 1970:" +ld.toepochday ());6LD = Localdate.of (2015,11,25);7SYSTEM.OUT.PRINTLN ("New Month Day:" +ld.getyear () + "-" +ld.getmonthvalue () + "-" +ld.getdayofmonth ());8 9LD = Ld.plusdays (1);TenSystem.out.println ("Plus day month Day:" +ld.getyear () + "-" +ld.getmonthvalue () + "-" +ld.getdayofmonth ()); One  ALD = Ld.minusdays (2); -System.out.println ("Minus Two days:" +ld.getyear () + "-" +ld.getmonthvalue () + "-" +ld.getdayofmonth ()); -  theLD = ld.plusmonths (1); -System.out.println ("Plus one month Date:" +ld.getyear () + "-" +ld.getmonthvalue () + "-" +ld.getdayofmonth ()); -  -LD = ld.minusmonths (1); +System.out.println ("Minus one months Date:" +ld.getyear () + "-" +ld.getmonthvalue () + "-" +ld.getdayofmonth ()); -  +Ld.plusweeks (1);//plus a week . ALd.plusyears (1);//Plus One year atLd.minusweeks (1);//minus a week . -Ld.minusyears (1);//minus one year .

Strong to We do not have to manually calculate these things, convenient, labor-saving, flexibility is very strong.

3. Support of some frameworks

Because the project is SPRING4+MYBATIS3, I only tested the support of both frameworks.

(1) Spring4 is supported by Localdate. The following format conversions are made when spring MVC receives parameters:

1 @RequestMapping ("/test")2publicvoid  method (HttpServletRequest Request,httpservletresponse response,3 @DateTimeFormat (pattern= "Yyyy-mm-dd") localdate localdate {4// receive processing logic 5 }

The receive parameter for spring MVC also needs to be explained: if it is an incoming date type, it needs to be formatted with the annotation @datetimeformat, or the 400 parameter error will be reported. If it is a bean object and contains a date or localdate type field, you also need to add the annotation @datetimeformat.

(2) MyBatis3 support to Localdate. There is still no support at this stage, we need to do some processing.

Plan one, modify MyBatis package source code. It will not be tried without the forced circumstances.

Scenario Two, add a handler processing type conversion. Online to find the treatment scheme, pro-test, completely can.

Only scenario two is described here, so Daniel can try out the scheme one.

First step: Create a converter

1  PackageCom.hfms.mybatis.type;2  3 Importjava.sql.CallableStatement;4 Importjava.sql.PreparedStatement;5 ImportJava.sql.ResultSet;6 Importjava.sql.SQLException;7 ImportJava.sql.Timestamp;8 ImportJava.time.LocalDateTime;9 Ten ImportOrg.apache.ibatis.type.BaseTypeHandler; One ImportOrg.apache.ibatis.type.JdbcType; A Importorg.apache.ibatis.type.MappedTypes; -  /** - * Type converter, take localdatetime as an example, the use of localdate need to make corresponding changes the   * -   **/ -@MappedTypes (LocalDateTime.class) -  Public classLocaldatetimetypehandlerextendsBasetypehandler<localdatetime> { +   - @Override +      Public voidSetnonnullparameter (PreparedStatement PS,intI, LocalDateTime parameter, Jdbctype jdbctype)throwsSQLException { A Ps.settimestamp (i, timestamp.valueof (parameter)); at     } -   - @Override -      PublicLocalDateTime Getnullableresult (ResultSet rs, String columnName)throwsSQLException { -Timestamp date =Rs.gettimestamp (columnName); -         if(Date = =NULL) { in             return NULL; -}Else { to             returndate.tolocaldatetime (); +         } -     } the   * @Override $      PublicLocalDateTime Getnullableresult (ResultSet RS,intCOLUMNINDEX)throwsSQLException {Panax NotoginsengTimestamp date =Rs.gettimestamp (columnindex); -         if(Date = =NULL) { the             return NULL; +}Else { A             returndate.tolocaldatetime (); the         } +     } -   $ @Override $      PublicLocalDateTime Getnullableresult (CallableStatement cs,intCOLUMNINDEX)throwsSQLException { -Timestamp date =Cs.gettimestamp (columnindex); -         if(Date = =NULL) { the             return NULL; -}Else {Wuyi             returndate.tolocaldatetime (); the         } -     } Wu}

Step two: Configure in Mybatis-config.xml

1 <typeHandlers>2     < package name= "Com.hfms.mybatis.type"/>3 </typeHandlers>

Step three: Use when creating objects:

1  Public class test{2  LocalDateTime LocalDateTime;    3 }

This can be used directly in the testhandler.xml.

Not to be continued ~ ~

Java8 the use of time-processing classes (Localdate ... )

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.