Reputation: 4141
How we cast a string into time type with mysql in java So String------->java.sql.time
thanks.
Upvotes: 7
Views: 24368
Reputation: 338326
java.time.LocalTime
The Question and other Answers use terribly flawed date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
To represent a time-only value, without a date, and without a time zone or offset-from-UTC, use java.time.LocalTime
class.
To parse text in standard ISO 8601 format:
LocalTime t = LocalTime.parse( "15:30" ) ;
Write to database with JDBC 4.2 and later:
myPreparedStatement.setObject( … , t ) ;
Read from database:
LocalTime t = myResultSet.getObject( … , LocalTime.class ) ;
Search Stack Overflow to learn more. Date-time matters have been addressed extensively. And see tutorial by Oracle.
Upvotes: 1
Reputation: 2080
You can use this code:
java.sql.Time.parse("String");
But that's deprecated, and replaced by DateFormat Parse.
Upvotes: 2
Reputation: 359776
It depends entirely on the format of your String
, so I would use a SimpleDateFormat
to parse the string into a java.util.Date
; then you can extract the millisecond time value from that Date and pass it into a java.sql.Time()
. Like this:
String s = /* your date string here */;
SimpleDateFormat sdf = new SimpleDateFormat(/* your date format string here */);
long ms = sdf.parse(s).getTime();
Time t = new Time(ms);
Upvotes: 14