Reputation: 5311
I am working on a Java project in which I have a Time
object in another column. But for some query purposes, I need the time as a part of Timestamp. For this reason, I decided to call the setTime
method of java.SQL.Timestamp, but it resets the date to 1970.
How can I only change the time part in java.SQL.Timestamp?
COde :
object.getTimestamp().setTime(object.getTTime().getTime());
Thank you.
Upvotes: 1
Views: 9447
Reputation: 1891
Work as with a normal java.util.Date
, update the time part using Calendar
, then update the timestamp with
setTime(long time)
Example
Calendar c=Calendar.getInstance();
c.setTimeInMillis(time.getTime());
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
ts.setTime(c.getTimeInMillis());
System.out.println(ts.getTime());
EDIT
Example 2
Timestamp ts;
//give some value to ts
Time time ;
//give some value to time
//Calendar based on ts
Calendar cTs=Calendar.getInstance();
cTs.setTimeInMillis(ts.getTime());
//Calendar based on time
Calendar cTime=Calendar.getInstance();
cTime.setTimeInMillis(time.getTime());
cTs.set(Calendar.HOUR_OF_DAY, cTime.get(Calendar.HOUR_OF_DAY));
cTs.set(Calendar.MINUTE, cTime.get(Calendar.MINUTE));
cTs.set(Calendar.SECOND, cTime.get(Calendar.SECOND));
cTs.set(Calendar.MILLISECOND, cTime.get(Calendar.MILLISECOND));
//set value of ts based on the modified cTs
ts.setTime(cTs.getTimeInMillis());
System.out.println(ts.getTime());
Upvotes: 2