java SimpleDateFormat setLenient用法

参考博客:https://www.cnblogs.com/my-king/p/4276577.html

SimpleDateFormat.setLenient(true) : 默认值true,不严格解析日期,会自动计算。

SimpleDateFormat.setLenient(false):严格解析日期,如果日期不合格就抛异常,不会自动计算。

例子:

package com.cy.test.date;

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

public class TestSimpleDateFormat {

    /**
     * dateFormat.setLenient 默认是true
     * setLenient(true),这种情况下java会把你输入的日期进行计算,比如55个月那么就是4年以后,这时候年份就会变成03年了
     * setLenient(false),这种情况下java不会把你输入的日期进行计算,比如55个月那么就是不合法的日期了,直接异常
     * @param args
     * @throws ParseException
     */
    public static void main(String[] args) throws ParseException {
        String dob= "1/55/1999";
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        dateFormat.setLenient(true);
        Date dateofbirth = dateFormat.parse(dob);
        System.out.println(dateofbirth);        //Tue Jul 01 00:00:00 CST 2003

        String dob2= "1/55/1999";
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd/MM/yyyy");
        dateFormat2.setLenient(false);
        Date dateofbirth2 = dateFormat2.parse(dob2);    //Exception in thread "main" java.text.ParseException: Unparseable date: "1/55/1999"
        System.out.println(dateofbirth2);
    }
}
原文地址:https://www.cnblogs.com/tenWood/p/11339983.html