Removing time (hh:mm:ss) from Date object

hi ppl

i'm trying to make a method to remove the hours, minutes, seconds information from a Date object.

the method should produce the following result:

Mon Jul 23 10:14:33 BST 2007

TO

Mon Jul 23 00:00:00 BST 2007

i've come up with the following that resolves the problem but, is this a good solution?

publicstaticvoid main(String[] args)throws Exception{

Date old1 =new Date();

Calendar cal = Calendar.getInstance();

cal.setTime(old1);

cal.add(Calendar.HOUR_OF_DAY, -cal.get(Calendar.HOUR_OF_DAY));

cal.add(Calendar.MINUTE, -cal.get(Calendar.MINUTE));

cal.add(Calendar.SECOND, -cal.get(Calendar.SECOND));

Date new1 = cal.getTime();

System.out.println("Old: " + old1);

System.out.println("New: " + new1);

}

thanks a lot

regards

andre

[1137 byte] By [peugaa] at [2007-11-27 11:23:33]
# 1

You could use an java.sql.Date. Those should be normalized to 12 o'clock GMT.

Or are you actually looking for SimpleDateFormat? Why don't you just ignore the time?

As for the calendar solution: you could just set the time fields to 0.

CeciNEstPasUnProgrammeura at 2007-7-29 15:01:22 > top of Java-index,Java Essentials,Java Programming...
# 2

i need a Date object has the result...

i think setting the fields to 0 should do it ...how could i let that pass :X ... really dumb!

thanks

peugaa at 2007-7-29 15:01:22 > top of Java-index,Java Essentials,Java Programming...
# 3

> i need a Date object has the result...

java.sql.Date extends java.util.Date.

CeciNEstPasUnProgrammeura at 2007-7-29 15:01:22 > top of Java-index,Java Essentials,Java Programming...
# 4

why do you say i should use the java.sql.Date instead of the util?

because of the timezone?

can you explain it to me?

peugaa at 2007-7-29 15:01:22 > top of Java-index,Java Essentials,Java Programming...
# 5

> You could use an java.sql.Date. Those should be

> normalized to 12 o'clock GMT.

No, it isn't normalized automatically! I thought that as well, but because I wasn't 100% sure, I ran a unit test lately, and I figured out, that it isn't! (I think it has something to do with the timezone.) It should be manually normalized though! (And probably it also will be, when you retrieve a sql.Date field from a db.) But this won't help the OP.

@OP: I also suggest just to set the field you don't want, to 0. And probably you also want to set the milliseconds to 0!

-Puce

Message was edited by:

Puce

Pucea at 2007-7-29 15:01:22 > top of Java-index,Java Essentials,Java Programming...