SimpleDateFormat和解析:解析不会因输入字符串日期错误而失败 [英] SimpleDateFormat and parsing: parse doesn't fail with wrong input string date

查看:127
本文介绍了SimpleDateFormat和解析:解析不会因输入字符串日期错误而失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

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

其中inputStringdd/MM/yyyy格式的字符串.

例如,如果inputString是40/02/2013,我将获得一个错误,而是parse方法返回2013年3月12日(12/03/2013). 我在抱怨什么?

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). What I'm wronging?

推荐答案

设置

指定日期/时间解析是否宽松.通过宽大的解析,解析器可以使用启发式方法来解释与该对象的格式不完全匹配的输入.通过严格的解析,输入必须匹配该对象的格式.

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.

以下代码:

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();
        }

    }
}

赠予:

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)

注释

  1. 如果对Java类有疑问,则应该阅读类文档.我不知道您问题的答案,我只搜索了该类,单击了parse方法链接并记下了另见部分. 您应该始终先搜索,并在问题中提及您的发现
  2. 延期日期的历史可追溯至激发孩子的想象力.
  1. When in doubt about a Java class, reading the class documentation should be your first step. 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. 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.

这篇关于SimpleDateFormat和解析:解析不会因输入字符串日期错误而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆