minil minil - 1 year ago 74
Java Question

java program to get the current date without timestamp

I need a java program to get the current date without timestamp

Date d = new Date();

gives me date and timestamp
But i need only date, without timestamp. I use this date to compare with another date object that does not have timestamp.

on printing

System.out.println("Current Date : " + d)

of d it should print May 11 2010 - 00:00:00 .

Answer Source

A java.util.Date object is a kind of timestamp - it contains a number of milliseconds since January 1, 1970, 00:00:00 UTC. So you can't use a standard Date object to contain just a day / month / year, without a time.

As far as I know, there's no really easy way to compare dates by only taking the date (and not the time) into account in the standard Java API. You can use class Calendar and clear the hour, minutes, seconds and milliseconds:

Calendar cal = Calendar.getInstance();

Do the same with another Calendar object that contains the date that you want to compare it to, and use the after() or before() methods to do the comparison.


Concerned fields modified for a good reset.

As explained into the Javadoc of java.util.Calendar.clear(int field) :

The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and the the resolution rule for the time of day is applied. Clearing one of the fields doesn't reset the hour of day value of this Calendar. Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.