【问题标题】:Why formatted date is giving previous century [duplicate]为什么格式化日期是上个世纪[重复]
【发布时间】:2013-04-09 12:56:09
【问题描述】:

我有 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" ));
    }

我们将不胜感激任何解决此问题的帮助。

【问题讨论】:

  • 才 2013 年,人们已经开始尝试再次削减世纪?

标签: java date date-format simpledateformat


【解决方案1】:

根据API documentationSimpleDateFormat解析两位数字的年份字段,所以结果是“SimpleDateFormat实例创建之前80年和之后20年”。

如果您想修改行为以更好地满足您的要求,您可以使用方法set2DigitYearStart 设置您的日期映射到的 100 年期间的开始。

【讨论】:

    【解决方案2】:

    来自 SimpleDateFormat javadoc:

    对于使用缩写年份模式(“y”或“yy”)进行解析, SimpleDateFormat 必须解释相对于某些年份的缩写年份 世纪。它通过将日期调整到 80 年前 以及创建 SimpleDateFormat 实例后的 20 年。

    在你的例子中,1950 年是今天之前的 80 年内。

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

    【讨论】:

      猜你喜欢
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 2018-01-07
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      相关资源
      最近更新 更多