Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to parse a date in MM/DD/YY format and adjust it to the current / previous century?

One of our customers wants to be able to enter a date with only 2 digits for the year component. The date will be in the past, so we want it to work for the previous century if the 2 digit year is after the current year, but work for the current century if the 2 digit year is equal to or less than the current year.

as of today 10/30/2008

01/01/01 = 01/01/2001

01/01/09 = 01/01/1909

This is a strange requirement, and I solved the problem, I just don't like my solution. It feels like there is a better way to do this.

Thanks for the 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;
}
like image 937
ScArcher2 Avatar asked Oct 30 '08 19:10

ScArcher2


2 Answers

Groovy script (easy enough to throw into java) demonstrating the point @bobince made about SimpleDateFormat.

import java.text.SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat('MM/dd/yy')
SimpleDateFormat fmt = new 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))
}

Yields

2001-01-01
2008-10-30
1909-01-01
like image 193
Ken Gentle Avatar answered Nov 05 '22 11:11

Ken Gentle


SimpleDateFormat already does two-digit year parsing for you, using the two-letter ‘yy’ format. (It'll still allow four digits, obviously.)

By default it uses now-80→now+20, so it's not exactly the same rule you propose, but it's reasonable and standardised (in the Java world at least), and can be overridden using set2DigitYearStart() if you want.

DateFormat informat= new SimpleDateFormat("MM/dd/yy");
DateFormat outformat= new SimpleDateFormat("MM/dd/yyyy");
return outformat.format(informat.parse(dateString));

In the longer term, try to migrate to ISO8601 date formatting (yyyy-MM-dd), because MM/dd/yy is approximately the worst possible date format and is bound to cause problems eventually.

like image 9
bobince Avatar answered Nov 05 '22 10:11

bobince