What is the most efficient way to disconnect time from a Java Date object?

What is the most efficient way to remove the temporary part from a Java date object using only classes from the JDK?

I have the following

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

In reset time until 00:00:00, I do the following

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

Now exit

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

Is there a better way to achieve the same result?

+4
source share
5 answers

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

In addition, you do not need to worry about locale settings, which can cause problems with converting strings to date.

+10
source

If you have general Apache permissions, 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 answer .)


Now, if you want smart code to be very fast and you don't mind using obsolete functions from java.util.Date , here is another solution. (Disclaimer: I would not use this code myself, but I tested it, and it works even on the days when DST starts and 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); 
+7
source

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

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

You can use Calendar if possible. Then you used cal.set(Calendar.MINUTE, 0) , etc.

It should be noted that if this is an option at all, you should use Joda-Time .

Related Questions

+1
source

Do you consider the time zone? I see that you have a BST right now, but what when the BST is finished? Do you still want to use BST?

In any case, I would advise you to take a look at DateMidnight from JodaTime and use this.

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

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

If you need to translate back go java.util.Date :

 Date myDate = d.toDate(); 
0
source
 myDate.setTime(myDate.getTime()-myDate.getTime()%86400000) 

can do the trick. Talk about fast and dirty.

0
source

All Articles