SimpleDateFormat的日期格式两位数年份转换

形如yy-MM-dd的年份转换,在simpleDateFormat中是这样处理的:

/* Initialize the fields we use to disambiguate ambiguous years. Separate
 * so we can call it from readObject().
 */
private void initializeDefaultCentury() {
     
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add( Calendar.YEAR, -80 );
    parseAmbiguousDatesAsAfter(calendar.getTime());
}

/* Define one-century window into which to disambiguate dates using
 * two-digit years.
 */
private void parseAmbiguousDatesAsAfter(Date startDate) {
     
    defaultCenturyStart = startDate;
    calendar.setTime(startDate);
    defaultCenturyStartYear = calendar.get(Calendar.YEAR);
}

两位数年份的世纪判断,采用的是当前时间减去80年的时间。
比如要转换一个“99-12-31”,当前时间是2019-11-28 18:00:00,在初始化世纪的时候,当前世纪是2019-80,也即1939-11-28 18:00:00
这个时候在转换‘99-12-31’的时候,就出现了1999-12-31的情况。
其实我期望的是转换成2099-12-31。
怎么办呢?
SimpleDataFormat提供了一个方法:
set2DigitYearStart
来看下源码:

/**
 * Sets the 100-year period 2-digit years will be interpreted as being in
 * to begin on the date the user specifies.
 *
 * @param startDate During parsing, two digit years will be placed in the range
 * startDate to startDate + 100 years.
 * @see #get2DigitYearStart
 * @since 1.2
 */
public void set2DigitYearStart(Date startDate) {
     
    parseAmbiguousDatesAsAfter(new Date(startDate.getTime()));
}

当当当~!
可以指定当前世纪的日期。

public static void main(String[] args) {
     
    SimpleDateFormat dateFormat = new SimpleDateFormat("yy:MM:dd");
    try {
     
        dateFormat.set2DigitYearStart(new Date(978278400000L));
        System.out.println(dateFormat.parse("00:01:01"));
    } catch (ParseException e) {
     
        e.printStackTrace();
    }
}

SimpleDateFormat的日期格式两位数年份转换_第1张图片
这样就解决了我的问题。

你可能感兴趣的:(java,dateformat)