为什么格式化日期给上个世纪

Jab*_*bir 2 java date date-format simpledateformat

我有4位数的日期.我偶然发现了那些在2050年之后的输入.在我的申请中 "0150"意味着January 01 2050.但是当我格式化它返回以下输出.

Sun Jan 01 00:00:00 PKT 1950




 public static Date getFormatDate( String newformat, String dateValue ) throws Exception {

        try {

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat( newformat );
            java.util.Date newdate = simpleDateFormat.parse( dateValue );
            return newdate;
        }
        catch( Exception e ) {
            System.out.println( "Exception in converting date format --->" + e );
            throw e;
        }
    }

    public static void main( String[] args ) throws Exception {        
        System.out.println(getFormatDate( "MMyy", "0150" ));
    }
Run Code Online (Sandbox Code Playgroud)

任何帮助解决这个问题将受到高度赞赏.

jar*_*bjo 6

根据API文档,SimpleDateFormat解析两位数字年份字段,以便结果"在创建SimpleDateFormat实例之前的80年之前和之后20年".

如果要修改行为以更好地匹配您的要求,可以使用该方法set2DigitYearStart设置日期映射到的100年期间的开头.


obo*_*ain 5

从SimpleDateFormat javadoc:

对于使用缩写年份模式("y"或"yy")进行解析,SimpleDateFormat必须解释相对于某个世纪的缩写年份.它通过将日期调整为创建SimpleDateFormat实例之前的80年和20年之后来实现此目的.

在你的情况下,1950年是在今天之前的80年.

为了获得正确的日期(2050),您必须调用SimpleDateFormat.set2DigitYearStart(Date).