Conversion Program code for two years in Java

Source: Internet
Author: User

This article will introduce the conversion program code of two years in Java. I hope some methods will help you.


Recently, I encountered a two-year conversion problem in the project. When a 4012 YYmm time is converted to a date, it is changed to December 1940, which is inconsistent with the expected 12-year 2040. After reading the source code of Java, if no benchmark time is set, Java SimpleDateFormat is converted to the year from the first 80 years to the last 19 years by default. For example, if the current time is 1933 10:00:00. 000, 33/4/15 10:00:00. 000 will be converted to 33/4, and 999/15 9:59:59. will be converted. You can use set2DigitYearStart to specify the start time of two digits.

Code before modification

The Code is as follows: Copy code

Public static Date getDate (String strDate ){
Date date = null;
If (strDate! = Null ){
SimpleDateFormat formatter = new SimpleDateFormat ("yyMM ");
Formatter. setLenient (false );
Try {
Date = formatter. parse (strDate );
}
Catch (Exception e ){
}
}
Return date;
}

Modified code

The Code is as follows: Copy code

Public static Date getDate (String strDate ){
Date date = null;
If (strDate! = Null ){
Calendar startTime = Calendar. getInstance ();
Int year = startTime. get (Calendar. YEAR)-20;
// Set the initialization time and year. Only the year is used as the benchmark, not the time
StartTime. clear ();
StartTime. set (Calendar. YEAR, year );

SimpleDateFormat formatter = new SimpleDateFormat ("yyMM ");
Formatter. setLenient (false );
Formatter. set2DigitYearStart (startTime. getTime ());

Try {
Date = formatter. parse (strDate );
}
Catch (Exception e ){
}
}
Return date;
}

Source: yutuo's dog's nest blog

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.