Java String到DateTime [英] Java String to DateTime

查看:102
本文介绍了Java String到DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json响应的字符串:

I have a string from a json response:

start: "2013-09-18T20:40:00+0000",
end: "2013-09-18T21:39:00+0000",

如何将此字符串转换为java DateTime对象?

How do i convert this string to a java DateTime Object?

我已尝试使用以下内容:

i have tried using the following:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
start = sdf.parse("2013-09-18T20:40:00+0000");

但是我只能创建一个Date对象。但是绑定在String中的时间是有必要的。

but with this i can only create a Date Object. But the time binded in the String is kinda essential.

任何帮助都非常感谢!

推荐答案

您可以创建Joda DateTime 对象从Java Date 对象,因为Java没有一个 DateTime 类。

You can create Joda DateTime object from the Java Date object, since Java does not have a DateTime class.

DateTime dt = new DateTime(start.getTime());






虽然 / code> Java类保存时间信息(这是您首先需要的),我建议您使用 Calendar 而不是 Date Java类。


Though the Date class of Java holds the time information as well(that's what you need in the first place), I suggest you to use a Calendar instead of the Date class of Java.

Calendar myCal = new GregorianCalendar();
myCal.setTime(date);

看看日历文档以获取有关如何更有效地使用它的更多信息。

Have a look at the Calendar docs for more info on how you can use it more effectively.

事情已经改变,现在甚至Java(Java 8要精确),有一个 LocalDateTime ZonedDateTime 类。对于转化,您可以查看此 SO答案(发布摘录)。

Things have changed and now even Java (Java 8 to be precise), has a LocalDateTime and ZonedDateTime class. For conversions, you can have a look at this SO answer(posting an excerpt from there).

给定: Date date = [some date]

1)LocalDateTime<<<即时<<日期

Instant instant = Instant.ofEpochMilli(date.getTime());
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

(2)日期<即时<< LocalDateTime

Instant instant = ldt.toInstant(ZoneOffset.UTC);
Date date = Date.from(instant);

这篇关于Java String到DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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