gpt4 book ai didi

java - 2 年日期的 SimpleDateFormat 问题

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:48:33 26 4
gpt4 key购买 nike

我试图理解两件事:

  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

最佳答案

简单日期格式 API:

对于解析,如果模式字母的数量超过 2,则年份按字面解释,而不管数字的数量。因此,使用模式“MM/dd/yyyy”,“01/11/12”解析为公元 12 年 1 月 11 日。

至于 lenient,当它设置为 false 时,解析会为无效日期抛出异常,例如 01/32/12,而在 lenient 模式下,此日期被视为 02/01/12。 SimpleDateFormat 内部使用 Calendar,关于宽大的细节可以在 Calendar API 中找到。

关于java - 2 年日期的 SimpleDateFormat 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18127845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com