开发者

What's the most efficient way to strip out the time from a Java Date object?

开发者 https://www.devze.com 2023-01-13 05:10 出处:网络
What\'s the most efficient way to remove the time portion from a Java date object using only Classes from within the JDK?

What's the most efficient way to remove the time portion from a Java date object using only Classes from within the JDK?

I have the following

myObject.getDate() = {java.util.Date}"Wed May 26 23:59:00 BST 2010"

To reset 开发者_开发百科the time back to 00:00:00, I'm doing the following

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date myDate = sdf.parse(sdf.format(myObject.getDate()));

The output is now

myDate = {java.util.Date}"Wed May 26 00:00:00 BST 2010"

Is there a better way to achieve the same result?


More verbose, but probably more efficient:

    Calendar cal = GregorianCalendar.getInstance();
    cal.setTime(date);
    // cal.set(Calendar.HOUR, 0);   // As jarnbjo pointed out this isn't enough
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

Also, you don't need to worry about locale settings, which may cause problems with string to date conversions.


If you have Apache commons, you can use DateUtils.truncate():

Date myDate = DateUtils.truncate(myObject.getDate(), Calendar.DATE)

(If you don't have access to Apache Commons, DateUtils.truncate() is implemented basically the same as kgiannakakis's answer.)


Now, if you want "clever" code that is very fast, and you don't mind using deprecated functions from java.util.Date, here is another solution. (Disclaimer: I wouldn't use this code myself. But I have tested it and it works, even on days when DST starts/ends.)

long ts = myObject.getDate().getTime() - myObject.getDate().getTimezoneOffset()*60000L;
Date myDate = new Date(ts - ts % (3600000L*24L));
myDate.setTime(myDate.getTime() + myDate.getTimezoneOffset()*60000L);


These methods are deprecated, but given a Date, you can do something like this:

Date d = ...;
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);

You should use a Calendar if possible. You'd then use the cal.set(Calendar.MINUTE, 0), etc.

It should be mentioned that if it's at all an option, you should use Joda-Time.

Related questions

  • Why were most java.util.Date methods deprecated?


Are you taking time zone into consideration? I see you have BST right now, but what when BST is over? Do you still wish to use BST?

Anyway, I'd suggest you have a look at DateMidnight from JodaTime and use that.

Things may vary depending on how you want to handle the time zones. But in it's simplest form, it should be as simple as:

DateMidnight d = new DateMidnight(myObject.getDate());

If you must convert back go java.util.Date:

Date myDate = d.toDate();


myDate.setTime(myDate.getTime()-myDate.getTime()%86400000)

might do the trick. Talk about quick&dirty.

0

精彩评论

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