Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: convert a time from today to a timestamp

Tags:

java

timestamp

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?

like image 862
Jon Cox Avatar asked Mar 02 '11 16:03

Jon Cox


People also ask

How do I convert a date to time stamp?

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.

Can we convert String to timestamp in Java?

Use TimeStamp. valueOf() to Convert a String to Timestamp in Java. Use Date. getTime() to Convert a String to Timestamp in Java.

How can I get 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.

How do I convert a String to time stamp?

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.


1 Answers

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

like image 64
Sean Patrick Floyd Avatar answered Oct 12 '22 04:10

Sean Patrick Floyd