Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove sub seconds part of Date object

Tags:

java

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.

like image 904
user339108 Avatar asked Sep 03 '10 10:09

user339108


People also ask

How do you remove moments from seconds?

You can use the moment npm module and remove the milliseconds using the split Fn. Save this answer.

How do I remove the seconds from a datetime column in Python?

If you just want strings, you could remove the trailing seconds with a regex ':\d\d$' .

How do I remove the time from a new date?

To remove the time from a date, use the getFullYear() , getMonth() and getDate() methods to get the year, month and date of the given date and pass the results to the Date() constructor. When values for the time components are not provided, they default to 0 . Copied!


3 Answers

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.

like image 137
Jon Skeet Avatar answered Oct 06 '22 01:10

Jon Skeet


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

}
like image 45
Erkan Haspulat Avatar answered Oct 06 '22 02:10

Erkan Haspulat


java.util.Calendar can help you.

    Calendar instance = Calendar.getInstance();
    instance.setTime(date);
    instance.clear(Calendar.SECOND);
    date = instance.getTime();
like image 32
Daniel De León Avatar answered Oct 06 '22 01:10

Daniel De León