这是Java DateFormat错误吗? [英] Is this a Java DateFormat bug?

查看:105
本文介绍了这是Java DateFormat错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该模式为 dd-MM-yyyy

The pattern is "dd-MM-yyyy"

我认为字符串 01-01-2010mwwwwwwwwwwwwwwwwww不满足该模式,但以下代码显示

I think the string "01-01-2010mwwwwwwwwwwwwwww" does not satisfy the pattern, but the following code shows the contrary.

任何人都可以解释原因吗?

Anyone can explain why?

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

    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");

    Date date = df.parse("01-01-2010mwwwwwwwwwwwwwww");

    System.out.println(date);
}

谢谢

推荐答案

parse方法不会尝试匹配整个输入字符串。也就是说,前缀 01-01-2010 匹配,就足够了。

The parse method does not try to match the entire input string. That is, the prefix 01-01-2010 matches, and that's enough.

来自 DateFormat.parse


从给定字符串的开头解析文本以产生日期。 该方法可能不会使用给定字符串的整个文本。






如果需要找出是否是完全匹配,则可以尝试以下操作:


If you need to figure out if it was a "complete match", you could try the following:

SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");

String strDate = "01-01-2010mwwwwwwwwwwwwwww";
ParsePosition pp = new ParsePosition(0);
Date date = df.parse(strDate, pp);
System.out.println("Complete match: " + (pp.getIndex() == strDate.length()));

strDate = "01-01-2010";
pp = new ParsePosition(0);
date = df.parse(strDate, pp);
System.out.println("Complete match: " + (pp.getIndex() == strDate.length()));

此打印文件

Complete match: false
Complete match: true

这篇关于这是Java DateFormat错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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