java.util.Date gets stored as 2010-09-03 15:33:22.246 when the SQL data type is timestamp, how do I set the sub seconds to zero (e.g. 246 in this case) prior to storing the record.
Asked
Active
Viewed 1.4k times
5 Answers
20
The simplest way would be something like:
long time = date.getTime();
date.setTime((time / 1000) * 1000);
In other words, clear out the last three digits of the "millis since 1970 UTC".
I believe that will also clear the nanoseconds part if it's a java.sql.Timestamp
.

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
1that time will be a long time ago! More like date.setTime(date.getTime() - date.getTime() % 1000); – Peter DeWeese Sep 03 '10 at 10:26
-
@JonSkeet How would I remove hours, minutes, and seconds from a millisecond value, leaving just the date? I have been doing the math but I can't seem to figure it out. – Churro Oct 01 '13 at 17:50
-
@Churro: Without a time zone, there *is* no date. You can construct a `Calendar` with the appropriate time zone, set the time in it, and then fetch the date from that. Or personally, I'd use Joda Time. – Jon Skeet Oct 01 '13 at 20:37
-
Cool mathematic solution! – Maciek Kreft Jun 07 '16 at 13:57
9
Here is an idea:
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("S");
Date d = new Date();
System.out.println(df.format(d));
Calendar c = Calendar.getInstance();
c.set(Calendar.MILLISECOND, 0);
d.setTime(c.getTimeInMillis());
System.out.println(df.format(d));
}

Erkan Haspulat
- 12,032
- 6
- 39
- 45
4
java.util.Calendar
can help you.
Calendar instance = Calendar.getInstance();
instance.setTime(date);
instance.clear(Calendar.SECOND);
date = instance.getTime();

Daniel De León
- 13,196
- 5
- 87
- 72
2
Here is another way by java 8 Instant api
LocalDateTime now = LocalDateTime.now();
Instant instant = now.atZone(ZoneId.systemDefault()).toInstant().truncatedTo(ChronoUnit.SECONDS);
Date date = Date.from(instant);
or
Date now = new Date();
Instant instant = now.toInstant().truncatedTo(ChronoUnit.SECONDS);
Date date = Date.from(instant);

Steve Park
- 1,979
- 27
- 33
0
Alternatively, you can use Apache Commons DateUtils, for example:
DateUtils.setMilliseconds(new Date(), 0);

br2000
- 969
- 11
- 12