格式为“2010年1月10日”的解析日期在Java中? (带顺序指标,st | nd | rd | th) [英] Parsing dates of the format "January 10th, 2010" in Java? (with ordinal indicators, st|nd|rd|th)

查看:263
本文介绍了格式为“2010年1月10日”的解析日期在Java中? (带顺序指标,st | nd | rd | th)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Java中解析2010年1月10日格式的日期。如何做到这一点?

I need to parse the dates of the format "January 10th, 2010" in Java. How can I do this?

如何处理顺序指标 st nd rd th 尾随日数?

How to handle the ordinal indicators, the st, nd, rd, or th trailing the day number?

推荐答案

String s = "January 10th, 2010";
DateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy");
System.out.println("" + dateFormat.parse(s.replaceAll("(?:st|nd|rd|th),", "")));

但您需要确保使用正确的 Locale 正确解析这个月名称。

but you need to make sure you are using the right Locale to properly parse the month name.

我知道您可以在 SimpleDateFormat 模式。但是在这种情况下,文本取决于信息,实际上与解析过程无关。

I know you can include general texts inside the SimpleDateFormat pattern. However in this case the text is dependent on the info and is actually not relevant to the parsing process.

这实际上是我能想到的最简单的解决方案。但我很乐意被误会。

This is actually the simplest solution I can think of. But I would love to be shown wrong.

您可以通过执行类似的操作来避免其中一个意见暴露的陷阱:

You can avoid the pitfalls exposed in one of the comments by doing something similar to this:

String s = "January 10th, 2010";
DateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy");
System.out.println("" + dateFormat.parse(s.replaceAll("(?<= \\d+)(?:st|nd|rd|th),(?= \\d+$)", "")));

这将允许您不匹配 Jath,2010年第10期例如。

This will allow you to not match Jath,uary 10 2010 for example.

这篇关于格式为“2010年1月10日”的解析日期在Java中? (带顺序指标,st | nd | rd | th)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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