将字符串转换为日期,快完成了! [英] Converting a String to Date, almost done!

查看:33
本文介绍了将字符串转换为日期,快完成了!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
将符合 ISO8601 的字符串转换为 java.util.Date

我正在尝试转换此字符串:

I'm trying to convert this String:

2011-06-07T14:08:59.697-07:00

到 Java 日期,到目前为止,这是我所做的:

To a Java Date, so far, here's what I did:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S");
Date date1 = sdf.parse("2011-06-07T14:08:59.697", new java.text.ParsePosition(0));

几乎一切都很好,除了最重要的部分,时区SimpleDateFormat 的问题是它期望 +/-hhmm 中的 TimeZone 而我的是 +/-hh:mm 格式.

Almost everything is good, except the most important part, the timezone !! The problem with SimpleDateFormat is that it expect a TimeZone in +/-hhmm and mine is in +/-hh:mm format.

另外,我不知道为什么,这有效:

Also, and I don't know why, this works:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S Z");
Date date1 = sdf.parse("2011-06-07T14:08:59.697 -0700", new java.text.ParsePosition(0));

但这不是(时区前的空格):

But this does not (the space before the timezone):

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SZ");
Date date1 = sdf.parse("2011-06-07T14:08:59.697-0700", new java.text.ParsePosition(0));

将这个日期 2011-06-07T14:08:59.697-07:00 转换为 java 日期的正确格式是什么?

What is the correct format to transform this date 2011-06-07T14:08:59.697-07:00 to a java date ?

感谢您的帮助!

推荐答案

这看起来像 XML 中使用的 ISO 8601 标准日期和时间格式.不幸的是,Java 的 SimpleDateFormat 不能正确支持该格式,因为它无法处理时区中的冒号.

That looks like the ISO 8601 standard date and time format as it is used in XML. Unfortunately, Java's SimpleDateFormat doesn't support that format properly, because it can't deal with the colon in the timezone.

但是,javax.xml 包包含可以处理这种格式的类.

However, the javax.xml package contains classes that can deal with this format.

String text = "2011-06-07T14:08:59.697-07:00";
XMLGregorianCalendar cal = DatatypeFactory.newInstance().newXMLGregorianCalendar(text);

如果你需要它作为 java.util.Calendar 那么你可以在它上面调用 toGregorianCalendar() :

If you need it as a java.util.Calendar then you can call toGregorianCalendar() on it:

Calendar c2 = cal.toGregorianCalendar();

当然你可以得到一个java.util.Date:

Date date = c2.getTime();

您还可以使用流行的 Joda Time 库,它本身支持这种格式(并且有很多处理日期和时间的 API 比 Java 的标准库更好).

You could also use the popular Joda Time library which natively supports this format (and has a much better API for dealing with dates and times than Java's standard library).

这篇关于将字符串转换为日期,快完成了!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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