当 str = 2011/12/12aaaaaaaaa 时 SimpleDateFormat parse(string str) 不会抛出异常?

发布于 2024-12-19 22:46:41 字数 404 浏览 2 评论 0原文

下面是一个示例:

public MyDate() throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
    sdf.setLenient(false);
    String t1 = "2011/12/12aaa";
    System.out.println(sdf.parse(t1));
}

2011/12/12aaa 不是有效的日期字符串。但是该函数打印“Mon Dec 12 00:00:00 PST 2011”并且不会抛出 ParseException。

谁能告诉我如何让 SimpleDateFormat 将“2011/12/12aaa”视为无效日期字符串并引发异常?

Here is an example:

public MyDate() throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
    sdf.setLenient(false);
    String t1 = "2011/12/12aaa";
    System.out.println(sdf.parse(t1));
}

2011/12/12aaa is not a valid date string. However the function prints "Mon Dec 12 00:00:00 PST 2011" and ParseException isn't thrown.

Can anyone tell me how to let SimpleDateFormat treat "2011/12/12aaa" as an invalid date string and throw an exception?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

奶气 2024-12-26 22:46:41

关于 parse(...) 的 JavaDoc 声明如下:

解析不一定使用到字符串末尾的所有字符

似乎您无法使 SimpleDateFormat 抛出异常,但您可以执行以下操作:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
sdf.setLenient(false);
ParsePosition p = new ParsePosition( 0 );
String t1 = "2011/12/12aaa";    
System.out.println(sdf.parse(t1,p));

if(p.getIndex() < t1.length()) {
  throw new ParseException( t1, p.getIndex() );
}

基本上,您检查解析是否消耗了整个字符串,如果不是,则输入无效。

The JavaDoc on parse(...) states the following:

parsing does not necessarily use all characters up to the end of the string

It seems like you can't make SimpleDateFormat throw an exception, but you can do the following:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
sdf.setLenient(false);
ParsePosition p = new ParsePosition( 0 );
String t1 = "2011/12/12aaa";    
System.out.println(sdf.parse(t1,p));

if(p.getIndex() < t1.length()) {
  throw new ParseException( t1, p.getIndex() );
}

Basically, you check whether the parse consumed the entire string and if not you have invalid input.

痕至 2024-12-26 22:46:41

检查日期是否有效
如果日期有效,以下方法将返回,否则将返回 false。

public boolean isValidDate(String date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
        Date testDate = null;
        try {
            testDate = sdf.parse(date);
        }
        catch (ParseException e) {
            return false;
        }
        if (!sdf.format(testDate).equals(date)) {
            return false;
        }
        return true;

    }

看看下面的类,它可以检查日期是否有效

**示例示例**

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

public class DateValidCheck {


    public static void main(String[] args) {

        if(new DateValidCheck().isValidDate("2011/12/12aaa")){
            System.out.println("...date is valid");
        }else{
            System.out.println("...date is invalid...");
        }

    }


    public boolean isValidDate(String date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
        Date testDate = null;
        try {
            testDate = sdf.parse(date);
        }
        catch (ParseException e) {
            return false;
        }
        if (!sdf.format(testDate).equals(date)) {
            return false;
        }
        return true;

    }

}

To chack whether a date is valid
The following method returns if the date is in valid otherwise it will return false.

public boolean isValidDate(String date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
        Date testDate = null;
        try {
            testDate = sdf.parse(date);
        }
        catch (ParseException e) {
            return false;
        }
        if (!sdf.format(testDate).equals(date)) {
            return false;
        }
        return true;

    }

Have a look on the following class which can check whether the date is valid or not

** Sample Example**

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

public class DateValidCheck {


    public static void main(String[] args) {

        if(new DateValidCheck().isValidDate("2011/12/12aaa")){
            System.out.println("...date is valid");
        }else{
            System.out.println("...date is invalid...");
        }

    }


    public boolean isValidDate(String date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
        Date testDate = null;
        try {
            testDate = sdf.parse(date);
        }
        catch (ParseException e) {
            return false;
        }
        if (!sdf.format(testDate).equals(date)) {
            return false;
        }
        return true;

    }

}
浅唱々樱花落 2024-12-26 22:46:41

可以使用 Java 8 LocalDate:

public static boolean isDate(String date) {
    try {
        LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        return true;
    } catch (DateTimeParseException e) {
        return false;
    }
}

如果输入参数为 "2011/12/12aaaaaaaaa",则输出为 false

如果输入参数为 "2011/12/12",则输出为 true

Java 8 LocalDate may be used:

public static boolean isDate(String date) {
    try {
        LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        return true;
    } catch (DateTimeParseException e) {
        return false;
    }
}

If input argument is "2011/12/12aaaaaaaaa", output is false;

If input argument is "2011/12/12", output is true

救星 2024-12-26 22:46:41

成功解析整个模式字符串后,SimpleDateFormat 停止评估要解析的数据。

After it successfully parsed the entire pattern string SimpleDateFormat stops evaluating the data it was given to parse.

隔岸观火 2024-12-26 22:46:41

查看方法文档,其中显示:如果无法解析指定字符串的开头,则出现 ParseException

带有javadoc的方法源代码:

/**
 * Parses text from the beginning of the given string to produce a date.
 * The method may not use the entire text of the given string.
 * <p>
 * See the {@link #parse(String, ParsePosition)} method for more information
 * on date parsing.
 *
 * @param source A <code>String</code> whose beginning should be parsed.
 * @return A <code>Date</code> parsed from the string.
 * @exception ParseException if the beginning of the specified string
 *            cannot be parsed.
 */
public Date parse(String source) throws ParseException
{
    ParsePosition pos = new ParsePosition(0);
    Date result = parse(source, pos);
    if (pos.index == 0)
        throw new ParseException("Unparseable date: \"" + source + "\"" ,
            pos.errorIndex);
    return result;
}

Take a look on the method documentation which says: ParseException if the beginning of the specified string cannot be parsed.

Method source code with javadoc:

/**
 * Parses text from the beginning of the given string to produce a date.
 * The method may not use the entire text of the given string.
 * <p>
 * See the {@link #parse(String, ParsePosition)} method for more information
 * on date parsing.
 *
 * @param source A <code>String</code> whose beginning should be parsed.
 * @return A <code>Date</code> parsed from the string.
 * @exception ParseException if the beginning of the specified string
 *            cannot be parsed.
 */
public Date parse(String source) throws ParseException
{
    ParsePosition pos = new ParsePosition(0);
    Date result = parse(source, pos);
    if (pos.index == 0)
        throw new ParseException("Unparseable date: \"" + source + "\"" ,
            pos.errorIndex);
    return result;
}
屌丝范 2024-12-26 22:46:41

只需设置 sdf.setLenient(false) 即可解决问题。

Simply setting sdf.setLenient(false) will do the trick..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文