Java – what is the best way to parse dates in mm / DD / yy format and adjust them to the current / previous century?
•
Java
One of our customers wants to be able to enter a date with only 2 digits in the year The date will be in the past, so if the two digit year is after this year, we want it to work in the last century, but if the two digit year is equal to or less than that year, it will work in the current century
As of today 10 / 30 / 2008
01/01/01 = 01/01/2001
01/01/09 = 01/01/1909
This is a strange request. I solved this problem. I just don't like my solution It feels like there's a better way to do this
Thank you for your help
public static String stupidDate(String dateString) { String twoDigitYear = StringUtils.right(dateString,2); String newDate = StringUtils.left(dateString,dateString.length() - 2); int year = NumberUtils.toInt(twoDigitYear); Calendar c = GregorianCalendar.getInstance(); int centuryInt = c.get(Calendar.YEAR) - year; newDate = newDate + StringUtils.left(Integer.toString(centuryInt),2) + twoDigitYear; return newDate; }
Solution
Groovy scripts (easy to throw into Java) demonstrate the @ bobice point about simpledateformat
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat('MM/dd/yy') java.text.SimpleDateFormat fmt = new java.text.SimpleDateFormat('yyyy-MM-dd') Calendar cal = Calendar.getInstance() cal.add(Calendar.YEAR,-100) sdf.set2DigitYearStart(cal.getTime()) dates = ['01/01/01','10/30/08','01/01/09'] dates.each {String d -> println fmt.format(sdf.parse(d)) }
Yeilds
2001-01-01 2008-10-30 1909-01-01
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码