java SimpleDateFormat类不会为无效格式抛出异常

SimpleDateFormat类不会为无效格式抛出异常

import java.text.ParseException;

public class Hello {

    public static void main(String[] args) throws ParseException {
        System.out.println(new java.text.SimpleDateFormat("yyyy-MM-dd").parse("23-06-2015"));
    }
}

为什么这会返回Sun Dec 05 00:00:00 GMT 28

SimpleDateFormat的Javadoc有关于重复模式字母的说法:

Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it’s needed to separate two adjacent fields

因此,对于解析,“yyyy-MM-dd”相当于“y-M-d”.

使用此模式,“23-06-2015”被解析为年= 23,月= 6,dayOfMonth = 2015.

默认情况下,从0023年6月1日开始计算,并计算2015天后日期,将您带到0028年12月5日.

您可以使用SimpleDateFormat.setLenient(false)更改此行为 – 禁用lenalent时,它将为超出范围的数字引发异常.这在Calendar.setLenient()中有适当的记录

请注意,对于Java 8中的新代码,避免使用旧的Date和Calendar类是个好主意.如果可以,请使用LocalDateTime.parse(CharSequence文本,DateTimeFormatter格式化程序).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值