SimpleDateFormat.setLenient(bool flag);方法

本文介绍如何使用Java中的SimpleDateFormat类来判断一个字符串是否为合法的日期格式,并通过设置setLenient参数来控制日期验证的宽松度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SimpleDateFormat.setLenient(bool flag);是一个可自动判定日期是否合法的方法,在使用过程中很方便;

使用方法例如:输入“2015.10.33”在SimpleDateFormat.setLenient(true);的时候可以输出;而在SimpleDateFormat.setLenient(false);抛出异常。

package date;

import java.text.SimpleDateFormat;

/**
 * Created by taoyongpan on 2016/10/12.
 */
public class JudgeDate {
    public static void main(String[]args)
    {
        String str="2007-5-32";
        if(isDate(str,"yyyy.MM.dd")|isDate(str,"yyyy-MM-dd"))
            System.out.print(str);
        else
            System.out.println("This is wrong");
    }
    public static  boolean isDate(String str_input,String rDateFormat){
        if (!isNull(str_input)) {
            SimpleDateFormat format = new SimpleDateFormat(rDateFormat);
            format.setLenient(false);
            try {
                format.format(format.parse(str_input));
            } catch (Exception e) {
                return false;
            }
            return true;
        }
        return false;

    }
    public static boolean isNull(String str){
        if(str==null)
            return true;
        else
            return false;
    }
}
输出结果是“This is wrong”
package date;

import java.text.SimpleDateFormat;

/**
 * Created by taoyongpan on 2016/10/12.
 */
public class JudgeDate {
    public static void main(String[]args)
    {
        String str="2007-5-32";
        if(isDate(str,"yyyy.MM.dd")|isDate(str,"yyyy-MM-dd"))
            System.out.print(str);
        else
            System.out.println("This is wrong");
    }
    public static  boolean isDate(String str_input,String rDateFormat){
        if (!isNull(str_input)) {
            SimpleDateFormat format = new SimpleDateFormat(rDateFormat);
            format.setLenient(true);
            try {
                format.format(format.parse(str_input));
            } catch (Exception e) {
                return false;
            }
            return true;
        }
        return false;

    }
    public static boolean isNull(String str){
        if(str==null)
            return true;
        else
            return false;
    }
}
 输出结果是“2007-5-32”;
综上 ,我们使用的过程中,要设置为false;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值