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