How to remove part of the second seconds of a Date object

java.util.Date is stored as 2010-09-03 15: 33: 22.246, when the SQL data type is a timestamp, how to set the hook seconds to zero (for example, 246 in this case) before saving the record.

+3
source share
5 answers

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));

}
+9
source

The easiest way is something like:

long time = date.getTime();
date.setTime((time / 1000) * 1000);

In other words, clear up the last three digits of the millis since 1970 UTC.

I believe that it will also clear the nanosecond part if it is java.sql.Timestamp.

+17
source

java.util.Calendar .

    Calendar instance = Calendar.getInstance();
    instance.setTime(date);
    instance.clear(Calendar.SECOND);
    date = instance.getTime();
+2

: java 8 Instant api

LocalDateTime now = LocalDateTime.now();
Instant instant = now.atZone(ZoneId.systemDefault()).toInstant().truncatedTo(ChronoUnit.SECONDS);
Date date = Date.from(instant);

Date now = new Date();
Instant instant = now.toInstant().truncatedTo(ChronoUnit.SECONDS);
Date date = Date.from(instant);
0

Apache Commons DateUtils, :

DateUtils.setMilliseconds(new Date(), 0);
0

Source: https://habr.com/ru/post/1763051/


All Articles