Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to remove the time part from java.util.Date? [duplicate]

Tags:

java

date

I want to implement a thread-safe function to remove the time part from java.util.Date.

I tried this way

private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
public static Date removeTimeFromDate(Date date) {
        Date returnDate = date;

        if (date == null) {
            return returnDate;
        }

        //just have the date remove the time
        String targetDateStr = df.format(date);
        try {
            returnDate = df.parse(targetDateStr);
        } catch (ParseException e) {
        }

        return returnDate;
}

and use synchronized or threadLocal to make it thread-safe. But it there any better way to implement it in Java. It seems this way is a bit verbose. I am not satisfied with it.

like image 668
Clark Bao Avatar asked Dec 13 '22 08:12

Clark Bao


2 Answers

A Date object holds a variable wich represents the time as the number of milliseconds since epoch. So, you can't "remove" the time part. What you can do is set the time of that day to zero, which means it will be 00:00:00 000 of that day. This is done by using a GregorianCalendar:

GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
gc.set(Calendar.HOUR_OF_DAY, 0);
gc.set(Calendar.MINUTE, 0);
gc.set(Calendar.SECOND, 0);
gc.set(Calendar.MILLISECOND, 0);
Date returnDate = gc.getTime();
like image 192
Martijn Courteaux Avatar answered Dec 14 '22 21:12

Martijn Courteaux


A Date holds an instant in time - that means it doesn't unambiguously specify a particular date. So you need to specify a time zone as well, in order to work out what date something falls on. You then need to work out how you want to represent the result - as a Date with a value of "midnight on that date in UTC" for example?

You should also note that midnight itself doesn't occur on all days in all time zones, due to DST transitions which can occur at midnight. (Brazil is a common example of this.)

Unless you're really wedded to Date and Calendar, I'd recommend that you start using Joda Time instead, as that allows you to have a value of type LocalDate which gets rid of most of these problems.

like image 33
Jon Skeet Avatar answered Dec 14 '22 21:12

Jon Skeet