开发者

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

开发者 https://www.devze.com 2023-04-13 09:51 出处:网络
This question already has answers here: Java Date cut off time information (20 answers) Closed 8 years ago.
This question already has answers here: Java Date cut off time information (20 answers) Closed 8 years ago.

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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号