使用正则表达式格式化字符串日期

时间:2015-08-10 12:07:43

标签: java regex

我有表示日期201510251010的字符串2015/10/25 10:10。我希望以第二种格式获取日期为String。

我有这段代码:

 String myString = "201510151235";
 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
 SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
 Date d = dateFormat.parse(myString);
 String s = dateFormat2.format(d);

它有效,但我认为这是丑陋的代码。有没有办法用正则表达式和replaceAll或类似的东西做同样的事情?

2 个答案:

答案 0 :(得分:2)

您可以尝试使用

Dispose

但我怀疑它看起来比你拥有的更具可读性,它肯定不如String myString = "201510151235"; String formatted = myString.replaceAll("(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1-$2-$3 $4:$5"); //or "$1/$2/$3 $4:$5"); 那么安全。

答案 1 :(得分:2)

AFAIK,对于日期,使用日期时间对象解析它们是一个很好的选择而不是正则表达式,因为通过这种方式,您可以支持不同的文化日期,否则对于不同的文化,模式可能会有所不同。所以,你的方式对我来说很好。