Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove milliseconds, seconds, minutes and hours from Date [duplicate]

Tags:

java

date

I ran into a problem where I wanted to compare two dates. However, I only wanted to compare Year, Month and Day. And this is what I can up with:

 private Date trim(Date date) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR, 0);
        return calendar.getTime();
    }

I user this function to trim all units but days, months and years.

Now, the question is what do you think about it? Do you know any other way to do so?

Thanks

like image 326
Adelin Avatar asked Jul 05 '13 23:07

Adelin


1 Answers

Do you really need to use java.util.Date ? If you can switch to joda time, you'll find very nice features like:

dateTime.dayOfMonth().roundFloorCopy()

which does exactly what you need.

like image 134
Costi Ciudatu Avatar answered Nov 09 '22 06:11

Costi Ciudatu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!