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

查看:35
本文介绍了解析格式“2010 年 1 月 10 日"的日期在爪哇?(带序数指标,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?

如何处理序数指标stndrdth 尾随日期?

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,uary 10 2010.

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

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

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