【问题标题】:Awkward Date Format in JavaJava中尴尬的日期格式
【发布时间】:2012-02-09 21:14:30
【问题描述】:

我无法解析这个日期:

Satu, 30 Octo 2010 06:00:00 EDT

我认为是

EEEE, dd MMMM yyyy HH:mm:ss Z

但它不起作用。我想将其格式化为

Saturday, October 30, 2010

我一直将 http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html 视为我的资源

【问题讨论】:

  • 您使用的是什么版本的 Java?
  • 一些预处理怎么样?将Satu, 30 Octo 2010 06:00:00 EDT 转换为Sat, 30 Oct 2010 06:00:00 EDT,即只需删除第 3 和第 12 个字符。让生活更简单! (如果你对正则表达式没问题,你也可以使用, 的位置和字符类型来概括它。)
  • 好的,我先将其作为字符串处理。无论如何,这是一种非常奇怪的日期格式。谢谢!

标签: java date simpledateformat


【解决方案1】:

老实说,我会放弃 Satu, 并从那时起进行解析。您不需要它,并且可以随时使用Calendar 来计算星期/月/年中的哪一天。请参阅here 了解 StringUtils 是什么。

String dateString = "Satu, 30 Octo 2010 06:00:00 EDT";

Map<String, String> weirdMonthMap = new HashMap<String, String>();
weirdMonthMap.put("Janu", "Jan");
//...
weirdMonthMap.put("Octo", "Oct");

for (String key: weirdMonthMap.keySet()) {
    dateString = StringUtils.replace(dateString, key, weirdMonthMap.get(key));
}

String[] pieces = StringUtils.split(dateString, ',');
if (pieces.length != 2)
    throw new IllegalArgumentException("Whoa! " + dateString);

dateString = pieces[1];

SimpleDateFormat format = new SimpleDateFormat(" dd MMM yyyy HH:mm:ss z");

System.out.println( format.parse(dateString) );

【讨论】:

  • 这对我不起作用。我认为问题在于Octo 不是十月的公认缩写,Satu 也不是星期六的缩写。 SimpleDateFormat 似乎通过使用一组特定的受支持名称来工作,而不是通过尝试匹配字符串前缀。
  • 是的,你说得对,我错过了 Octo。进行全局字符串替换或正则表达式可能是最简单的
【解决方案2】:
Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number. 

MMM 不是“前三个字母”的意思。

MMM 和 MMMMMMMMMMMMMM 都是一样的。

所以你的输入应该是“Oct”或“October”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多