有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有四位数的日期。我遇到了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" ));
    }

我们将非常感谢您对解决此问题的任何帮助


共 (1) 个答案

  1. # 1 楼答案

    从SimpleDataFormat javadoc:

    For parsing with the abbreviated year pattern ("y" or "yy"), SimpleDateFormat must interpret the abbreviated year relative to some century. It does this by adjusting dates to be within 80 years before and 20 years after the time the SimpleDateFormat instance is created.

    就你而言,1950年是离今天不到80年的时间

    为了得到正确的日期(2050年),你必须打电话给SimpleDateFormat.set2DigitYearStart(Date)