Java String to DateTime

sn0*_*0ep 8 java datetime

I have a string from a json response:

start: "2013-09-18T20:40:00+0000",
end: "2013-09-18T21:39:00+0000",
Run Code Online (Sandbox Code Playgroud)

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");
Run Code Online (Sandbox Code Playgroud)

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

Any Help is greatly appreciated!

Bac*_*ash 7

你不需要一个DateTime物体.java.util.Date也存储时间.

int hours = start.getHours(); //returns the hours
int minutes = start.getMinutes(); //returns the minutes
int seconds = start.getSeconds(); //returns the seconds
Run Code Online (Sandbox Code Playgroud)

正如RJ所说,这些方法已被弃用,因此您可以使用java.util.Calendar该类:

Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse("2013-09-18T20:40:00+0000"));
int hour = calendar.get(Calendar.HOUR); //returns the hour
int minute = calendar.get(Calendar.MINUTE); //returns the minute
int second = calendar.get(Calendar.SECOND); //returns the second
Run Code Online (Sandbox Code Playgroud)

注意:在我的结尾,sdf.parse("2013-09-18T20:40:00+0000")发射一个

java.text.ParseException: Unparseable date: "2013-09-18T20:40:00+0000"
    at java.text.DateFormat.parse(DateFormat.java:357)
    at MainClass.main(MainClass.java:16)
Run Code Online (Sandbox Code Playgroud)


Sud*_*hul 5

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

DateTime dt = new DateTime(start.getTime());
Run Code Online (Sandbox Code Playgroud)

虽然DateJava类也保存了时间信息(这就是你首先需要的),但我建议你使用Java Calendar而不是DateJava类.

Calendar myCal = new GregorianCalendar();
myCal.setTime(date);
Run Code Online (Sandbox Code Playgroud)

有关如何更有效地使用它的更多信息,请查看日历文档.


事情发生了变化,现在甚至Java(准确地说是Java 8)都有一个LocalDateTimeZonedDateTime类.对于转换,您可以查看此SO答案(从那里发布摘录).

鉴于: Date date = [some date]

(1)LocalDateTime << Instant << Date

Instant instant = Instant.ofEpochMilli(date.getTime());
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
Run Code Online (Sandbox Code Playgroud)

(2)日期<< Instant << LocalDateTime

Instant instant = ldt.toInstant(ZoneOffset.UTC);
Date date = Date.from(instant);
Run Code Online (Sandbox Code Playgroud)