Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

Java String to DateTime

I have a string from a json response:

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

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");

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't need a DateTime object. java.util.Date stores the time too.

int hours = start.getHours(); //returns the hours
int minutes = start.getMinutes(); //returns the minutes
int seconds = start.getSeconds(); //returns the seconds

As R.J says, these methods are deprecated, so you can use the java.util.Calendar class:

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

Note: on my end, sdf.parse("2013-09-18T20:40:00+0000") fires a

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...