包含2年日期的SimpleDateFormat问题 [英] SimpleDateFormat problems with 2 year date

查看:0
本文介绍了包含2年日期的SimpleDateFormat问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在试着理解两件事:

  1. 以下代码为什么不抛出异常(因为SimpleDateFormat不宽松)
  2. 它没有抛出异常,但为什么它将年份解析为0013(而不是using the rules here从今天起+80:-20年)

代码如下

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TestDate {
    public static void main(String[] args) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        format.setLenient(false);
        Date date = format.parse("01/01/13"); // Since this only has a 2 digit year, I would expect an exception to be thrown

        System.out.println(date); // Prints Sun Jan 01 00:00:00 GMT 13

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        System.out.println(cal.get(Calendar.YEAR)); // Prints 13
    }
}

如果有区别,我在Ubuntu上使用的是Java 1.6.0_38-B05

推荐答案

SimpleDateFormat接口:

对于解析,如果模式字母的数量大于2,则按字面解释年份,而不考虑位数。因此,使用"MM/dd/yyyy"模式,"01/11/12"将解析为公元12年1月11日

对于lenient,当设置为FALSE时,解析会抛出无效日期的异常,例如01/32/12,而在lenient模式下,该日期被视为02/01/12。SimpleDateFormat内部使用Calendar,宽大的详细信息可以在Calendar接口中找到。

这篇关于包含2年日期的SimpleDateFormat问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆