使 SimpleDateFormat.parse() 在无效日期上失败(例如,月份大于 12) [英] Make SimpleDateFormat.parse() fail on invalid dates (e.g. month is greater than 12)

查看:25
本文介绍了使 SimpleDateFormat.parse() 在无效日期上失败(例如,月份大于 12)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 java.text.SimpleDateFormat 来解析 "yyyyMMdd" 形式的字符串.

I'm using java.text.SimpleDateFormat to parse strings of the form "yyyyMMdd".

如果我尝试解析月份大于 12 的字符串,它不会失败,而是会滚动到下一年.完整的可运行重现:

If I try to parse a string with a month greater than 12, instead of failing, it rolls over to the next year. Full runnable repro:

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

public class ParseDateTest {

    public static void main(String[] args) throws ParseException {

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date result = format.parse("20091504"); // <- should not be a valid date!
        System.out.println(result); // prints Thu Mar 04 00:00:00 CST 2010
    }
 }

我宁愿抛出一个 ParseException.

是否有任何强制异常发生的非黑客方法?.我的意思是,我不想手动检查月份是否大于 12.这有点荒谬.

Is there any non-hacky way of forcing the exception to happen?. I mean, I don't want to manually check if the month is greater than 12. That's kind of ridiculous.

感谢您的任何建议.

注意:我已经知道 Joda Time,但我需要在没有外部库的普通 JDK 中完成.

NOTE: I already know about Joda Time, but I need this done in plain JDK without external libraries.

推荐答案

你需要让它非宽松.因此,

format.setLenient(false);

应该这样做.

这篇关于使 SimpleDateFormat.parse() 在无效日期上失败(例如,月份大于 12)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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