I am using Java 6, and I have a time from the current date as a string, like this: 14:21:16
, and I need to convert this to a Timestamp
object to store in a database.
However there seems to be no good way to get a Timestamp from this. Timestamp.valueOf(String)
is quite close, but requires a date. Is there a good way to make a Timestamp object from such a string?
Use the getTime() method to convert a date to a timestamp, e.g. new Date(). getTime() . The getTime method returns the number of milliseconds elapsed between the 1st of January, 1970 and the given date.
Use TimeStamp. valueOf() to Convert a String to Timestamp in Java. Use Date. getTime() to Convert a String to Timestamp in Java.
Java SQL Timestamp getTime() function with examples The getTime() function is a part of Timestamp class of Java SQL. The function is used to get the time of the Timestamp object. The function returns time in milliseconds which represents the time in milliseconds after 1st January 1970.
To convert a date string to a timestamp: Pass the date string to the Date() constructor. Call the getTime() method on the Date object. The getTime method returns the number of milliseconds since the Unix Epoch.
How about this:
final String str = "14:21:16";
final Timestamp timestamp =
Timestamp.valueOf(
new SimpleDateFormat("yyyy-MM-dd ")
.format(new Date()) // get the current date as String
.concat(str) // and append the time
);
System.out.println(timestamp);
Output:
2011-03-02 14:21:16.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With