Java中使用yyyy-MM-dd日期格式进行转换,转换字符串为999-999-999时,没有出现异常,反倒是执行通过了。

mlinge-奋斗吧 2013-03-01 03:20:51
回答之前请先阅读下面的代码:
public static void main(String[] args) throws Exception{
String strDate = "999-999-999";// 定义日期字符串
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");// 定义日期格式
Date date = null;
try {
date = format.parse(strDate);// 将字符串转换为日期
} catch (ParseException e) {
System.out.println("日期格式有误,请给出正确的日期格式");
return;
}
System.out.println(format.format(date));
}
运行结果是:1084-11-23
预想的结果应该是:日期格式有误,请给出正确的日期格式,但是却输出了日期,很纳闷,求解。
...全文
854 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
微风飘过 2013-03-01
  • 打赏
  • 举报
回复
这个应该算是时间格式化的一个小错误把,如果会出现这种情况你在格式化之前先判断一下就可以了
mlinge-奋斗吧 2013-03-01
  • 打赏
  • 举报
回复
谢谢大家的回答,已经搞定了。 在date = format.parse(strDate)前面加上format.setLenient(false)就行了。 意思是【指定日期/时间解析是否不严格。进行不严格解析时,解析程序可以使用启发式的方法来解释与此对象的格式不精确匹配的输入。进行严格解析时,输入必须匹配此对象的格式。 】
liangzhicai2009 2013-03-01
  • 打赏
  • 举报
回复
它应该会把日月多出来的加到年上,这个在转化之前一般自己做一下验证吧
失落夏天 2013-03-01
  • 打赏
  • 举报
回复
感觉真没必要太纠结于那些太细节的。
时光的留念 2013-03-01
  • 打赏
  • 举报
回复
正常下一般人都是调用format方法来去格式化时间。 parse方法比较繁琐
/**
     * 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;
    }
mlinge-奋斗吧 2013-03-01
  • 打赏
  • 举报
回复
已经搞定了,在date = format.parse(strDate)前面加上format.setLenient(false)就行了。意思是【严格的解析,输入必须匹配这个对象的格式。】

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧