Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String to DateTime

Tags:

java

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!

like image 748
sn0ep Avatar asked Sep 16 '13 08:09

sn0ep


People also ask

How do I convert a string to a datetime?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.


1 Answers

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)
like image 78
BackSlash Avatar answered Oct 01 '22 05:10

BackSlash