I have String value of 08:03:10 pm, and I want to convert it into time. How can I do this in Java?
Asked
Active
Viewed 3.8k times
10
-
11Thats such a common question, it could have been asked 10 times this week. :) I am guessing google is broken again. – Peter Lawrey Jan 03 '11 at 13:57
-
In fact it looks like Chamal has asked this twice today. – jzd Jan 03 '11 at 14:53
-
possible duplicate of [Java string to date conversion](http://stackoverflow.com/questions/4216745/java-string-to-date-conversion). Even closer duplicate is [Convert Java string to Time, NOT Date](http://stackoverflow.com/q/18604408/642706). – Basil Bourque Jul 23 '15 at 05:16
3 Answers
25
String str = "08:03:10 pm";
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
Date date = formatter.parse(str);
Must See

jmj
- 237,923
- 42
- 401
- 438
-
2
-
well, chamal want time not date.. although java.sql.Time is a thin wrapper around date, it is better abstraction for time . – Gursel Koca Jan 03 '11 at 14:02
-
3I would also suggest conversion to Time (i.e. : `Time time = new Time(date.getTime())` ) because of 2 reasons : 1 - OP has specifically asked for a `Time` object instead of a `Date` object ,and 2(which back up 1) - maybe he has some bad API, which can not be changed(e.g. : `Time getTime(String s)` - it cannot return a `Date` , because it will result in a compiler error). – Daniel Apr 12 '14 at 19:25
-
6
If you omit the period, it is very easy. Just call the java.sql.Time.valueof()
method instead of the Time time = new Time("20:03:10");
method.

Community
- 1
- 1

Gursel Koca
- 20,940
- 2
- 24
- 34