Java: convert time from today to timestamp

I am using Java 6, and I have time from the current date as a string, for example: 14:21:16and I need to convert this to Timestampan object to store in the database.

However, there seems to be no good way to get the timestamp out of there. Timestamp.valueOf(String)pretty close, but a date is required. Is there a good way to make a Timestamp object from such a string?

+5
source share
6 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);

Conclusion:

2011-03-02 14: 21: 16.0

+5
source

Joda Time, LocalTime LocalDate, a LocalDateTime, Instant, , . ( LocalTime.toDateTimeToday(DateTimeZone).)

Timestamp(long).

(, SimpleDateFormat Joda Time, ...), , , Timestamp(long). ( Joda Time , , - " " " " .)

+6

, API, :

    // Get today date and time.
    Calendar c1 = Calendar.getInstance();
    c1.setTime(new Date()); 

    // Get the required time of day, copy year, month, day.
    Calendar c2 = Calendar.getInstance();
    c2.setTime(java.sql.Time.valueOf("14:21:16"));
    c2.set(Calendar.YEAR, c1.get(Calendar.YEAR));
    c2.set(Calendar.MONTH, c1.get(Calendar.MONTH));
    c2.set(Calendar.DAY_OF_MONTH, c1.get(Calendar.DAY_OF_MONTH));

    // Construct required java.sql.Timestamp object.
    Timestamp time = new Timestamp(c2.getTimeInMillis());

    Let see what we've done.
    System.out.println(time);

, java.sql.Time.valueOf "HH: MM: SS" . SimpleDateFormat.

+4

org.apache.commons.lang.time.DateUtils:

Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);    
DateFormat df = new SimpleDateFormat("HH:mm:ss");
Date time = df.parse("14:21:16");
Timestamp time = new Timestamp(today.getTime() + time.getTime());
+1
0
String str = "14:21:16";
DateFormat formatter = new SimpleDateFormat("HH:mm:ss"); 
Date date = formatter.parse(str); 
Timestamp timestamp = new Timestamp(date.getTime());
0

All Articles