如何使用Regex使用SimpleDateFormat解析日期

时间:2017-04-05 21:32:20

标签: java regex simpledateformat

在Java中,我们可以使用SimpleDateFormat来解析如下的日期:

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date d = sdf.parse("12/21/2012"); //matched to December 21, 2012

但如果我们的日期更改为

Date d = sdf.parse("12-21-2012"); //ParseException!!

有一种简单的方法可以通过混合正则表达式将此功能扩展到所有数字集吗?换句话说,只要格式匹配,我不关心分隔符是什么。 E.G:

SimpleDateFormat sdf = new SimpleDateFormat("MM[^0-9]dd[^0-9]yyyy");
Date d = sdf.parse("12/21/2012"); //matched to December 21, 2012
Date d = sdf.parse("12-21-2012"); //matched to December 21, 2012

1 个答案:

答案 0 :(得分:0)

您不能将java.text.SimpleDateFormat与通用格式一起使用。当您想要解析或格式化java.util.Date时,您需要有一个明确定义的格式。