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

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

问题描述


可能重复:

将符合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 ?

感谢您的帮助!

推荐答案

看起来像ISO 8601标准的日期和时间格式,因为它在XML中使用。不幸的是,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 其中:

And ofcourse you can get a java.util.Date out of that:

Date date = c2.getTime();

您还可以使用流行的 Joda Time 库,其原生支持此格式(并且具有比Java标准库更好的处理日期和时间的API)。

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天全站免登陆