简体   繁体   English

SimpleDateFormat和解析:解析不会因错误的输入字符串日期而失败

[英]SimpleDateFormat and parsing: parse doesn't fail with wrong input string date

I'm using 我正在使用

java.util.Date date;
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
  date = sdf.parse(inputString);
} catch (ParseException e) {
  e.printStackTrace();
}

where inputString is a string in the dd/MM/yyyy format. 其中inputStringdd/MM/yyyy格式的字符串。

If the inputString is, for example, 40/02/2013, I would to obtain an error, instead the parse method returns the Date 12 March 2013 (12/03/2013). 例如,如果inputString是40/02/2013,我将获得一个错误,而parse方法将返回Date 2013年3月12日(2013年3月12日)。 What I'm wronging? 我错了什么?

Set the Leniency bit : 设置宽松位

public void setLenient(boolean lenient)

Specify whether or not date/time parsing is to be lenient. 指定日期/时间解析是否宽松。 With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. 通过宽松的解析,解析器可以使用启发式来解释与该对象的格式不完全匹配的输入。 With strict parsing, inputs must match this object's format. 通过严格的解析,输入必须与此对象的格式匹配。

The following code: 以下代码:

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Tester {
    public static void main(String[] argv) {
        java.util.Date date;
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        // Lenient
        try {
            date = sdf.parse("40/02/2013");
            System.out.println("Lenient date is :                  "+date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // Rigorous
        sdf.setLenient(false);

        try {
            date = sdf.parse("40/02/2013");
            System.out.println("Rigorous date (won't be printed!): "+date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }
}

Gives: 得到:

Lenient date is :                  Tue Mar 12 00:00:00 IST 2013
java.text.ParseException: Unparseable date: "40/02/2013"
    at java.text.DateFormat.parse(DateFormat.java:357)

Notes 笔记

  1. When in doubt about a Java class, reading the class documentation should be your first step. 如果对Java类有疑问,阅读类文档应该是您的第一步。 I didn't know the answer to your question, I just Googled the class, clicked on the parse method link and noted the See Also part. 我不知道你的问题的答案,我只是用Google搜索了这个类,点击了解析方法链接并注意到了See Also部分。 You should always search first, and mention your findings in the question 您应该首先搜索,并在问题中提及您的发现
  2. Lenient dates have a respectable history of bypassing censorship and inspire children's' imagination . 宽容的约会有一个令人尊敬的历史绕过审查制度激发孩子们的想象力

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM