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.
14:21:16
Timestamp
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?
Timestamp.valueOf(String)
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
Joda Time, LocalTime LocalDate, a LocalDateTime, Instant, , . ( LocalTime.toDateTimeToday(DateTimeZone).)
LocalTime
LocalDate
LocalDateTime
Instant
LocalTime.toDateTimeToday(DateTimeZone)
Timestamp(long).
Timestamp(long)
(, SimpleDateFormat Joda Time, ...), , , Timestamp(long). ( Joda Time , , - " " " " .)
SimpleDateFormat
, 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.
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());
(, unix?), . , , , .
java.sql.Time
http://download.oracle.com/javase/1.4.2/docs/api/java/sql/Time.htm
String str = "14:21:16"; DateFormat formatter = new SimpleDateFormat("HH:mm:ss"); Date date = formatter.parse(str); Timestamp timestamp = new Timestamp(date.getTime());