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

后端 未结 5 1749
野趣味
野趣味 2020-12-11 02:37

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

相关标签:
5条回答
  • 2020-12-11 02:52

    How about this:

    public static String anEasierStupidDateWithNoStringParsing(String dateString) {
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
    
        //handling ParseExceptions is an exercise left to the reader!
        Date date = df.parse(dateString);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
    
        Calendar now = Calendar.getInstance();
        if (cal.after(now)) {
            cal.add(Calendar.YEAR, -100);
        }
    
        return cal;
    }
    

    In other words, let SimpleDateFormat parse the String and just adjust the year to be the previous century if SimpleDateFormat (which has it's own rules for interpreting year strings) returns a date that is after the current date.

    This would guarantee that all dates returned are in the past. However, it doesn't account for any dates that might be parsed as before this past century - for example, with the format MM/dd/yyyy, a date string like "01/11/12" parses to Jan 11, 12 A.D.

    0 讨论(0)
  • 2020-12-11 03:03

    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.

    0 讨论(0)
  • 2020-12-11 03:05

    If Joda Time is an option:

    String inputDate = "01/01/08";
    // assuming U.S. style date, since it's not clear from your original question
    DateTimeFormatter parser = DateTimeFormat.forPattern("MM/dd/yy");
    DateTime dateTime = parser.parseDateTime(inputDate);
    // if after current time
    if (dateTime.isAfter(new DateTime())) {
        dateTime = dateTime.minus(Years.ONE);
    }
    
    return dateTime.toString("MM/dd/yyyy");
    

    I know Joda Time isn't part of Java SE, and as I've said in another thread, I usually do not condone using a third-party library when there's a Java library that does the same thing. However, the person who is developing Joda Time is also leading JSR310 - the Date and Time API that'll make it into Java 7. So I Joda Time is basically going to be in future Java releases.

    0 讨论(0)
  • 2020-12-11 03:11
    Date deliverDate = new SimpleDateFormat("MM/dd/yy").parse(deliverDateString);
    String dateString2 = new SimpleDateFormat("yyyy-MM-dd").format(deliverDate);
    

    Working for me.

    0 讨论(0)
  • 2020-12-11 03:13

    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
    
    0 讨论(0)
提交回复
热议问题