How to handle date formatting problems in Java

Source: Internet
Author: User
Tags string format

1. The simplest way is to annotate the corresponding object

Here's an example:

@DateTimeFormat (pattern= "YYYY-MM-DD")
@JsonFormat (pattern= "Yyyy-mm-dd", timezone = "gmt+8")
Private Date valuedate;

Note: TimeZone = "gmt+8" must be added, or less one day

If your field is a date format, as defined above, but if you are using MyBatis, you must not write the type timestamp in MyBatis, otherwise you will get an error.

The correct wording is as follows:

Property column

<resultmap id= "Baseresultmap" type= "Com.cn.demo.domain.Card" >

<result column= "Createtime" property= "Createtime"/>

</resultMap>

The error is spelled as follows:

<resultmap id= "Baseresultmap" type= "Com.cn.demo.domain.Card" >

<result column= "Createtime" property= "Createtime" jdbctype= "TIMESTAMP"/>

</resultMap>

In short, it involves to the date format of place can not add jdbctype= "TIMESTAMP"

Note: the date type in the MySQL database displays only the month and day, and the datetime type shows the date

2. When the controller layer is converted to date, the code is as follows:

Date date = new SimpleDateFormat ("Yyyy-mm-dd", Locale.getdefault ()). Parse (valuedate);

Where Valuedate is the data passed in, but the string format to be passed in the same format as "YYYY-MM-DD", otherwise it will report an exception

How to handle date formatting problems in Java

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.