[java] Java program to get the current date without timestamp

I need a Java program to get the current date without a timestamp:

Date d = new Date();

gives me date and timestamp.

But I need only the date, without a timestamp. I use this date to compare with another date object that does not have a timestamp.

On printing

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

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

This question is related to java

The answer is


private static final DateFormat df1 = new SimpleDateFormat("yyyyMMdd"); 
    private static Date NOW = new Date();
    static {
        try {
            NOW = df1.parse(df1.format(new Date()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

You could use

// Format a string containing a date.
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.util.Calendar.*;

Calendar c = GregorianCalendar.getInstance();
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
// -> s == "Duke's Birthday: May 23, 1995"

Have a look at the Formatter API documentation.


I did as follows and it worked: (Current date without timestamp)

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date today = dateFormat.parse(dateFormat.format(new Date()));

I think this will work. Use Calendar to manipulate time fields (reset them to zero), then get the Date from the Calendar.

Calendar c = GregorianCalendar.getInstance();
c.clear( Calendar.HOUR_OF_DAY );
c.clear( Calendar.MINUTE );
c.clear( Calendar.SECOND );
c.clear( Calendar.MILLISECOND );
Date today = c.getTime();

Or do the opposite. Put the date you want to compare to in a calendar and compare calendar dates

Date compareToDate;  // assume this is set before going in.
Calendar today = GregorianCalendar.getInstance();
Calendar compareTo = GregorianCalendar.getInstance();
compareTo.setTime( compareToDate );
if( today.get( Calendar.YEAR ) == compareTo.get( Calendar.YEAR ) &&
    today.get( Calendar.DAY_OF_YEAR  ) == compareTo.get( Calendar.DAY_OF_YEAR  ) ) {
  // They are the same day!
}

Use DateFormat to solve this problem:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dateFormat2 = new SimpleDateFormat("MM-dd-yyyy");
print(dateFormat.format(new Date()); // will print like 2014-02-20
print(dateFormat2.format(new Date()); // will print like 02-20-2014

  DateFormat dateFormat = new SimpleDateFormat("MMMM dd yyyy");
  java.util.Date date = new java.util.Date();
  System.out.println("Current Date : " + dateFormat.format(date));

Also you can use apache commons lib DateUtils.truncate():

Date now = new Date();
Date truncated = DateUtils.truncate(now, Calendar.DAY_OF_MONTH);

Time will be set to 00:00:00 so you can work with this date or print it formatted:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

System.out.println(dateFormat.format(now);        // 2010-05-11 11:32:47
System.out.println(dateFormat.format(truncated);  // 2010-05-11 00:00:00

Here is my code for get only date:

Calendar c=Calendar.getInstance();
DateFormat dm = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date date = new java.util.Date();
System.out.println("current date is :    " + dm.format(date));

You can get by this date:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
print(dateFormat.format(new Date());

Here is full Example of it.But you have to cast Sting back to Date.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//TODO OutPut should LIKE in this format MM dd yyyy HH:mm:ss.SSSSSS
public class TestDateExample {

    public static void main(String args[]) throws ParseException {
        SimpleDateFormat changeFormat = new SimpleDateFormat("MM dd yyyy HH:mm:ss.SSSSSS");
         Date thisDate = new Date();//changeFormat.parse("10 07 2012"); 
         System.out.println("Current Date : " + thisDate);
         changeFormat.format(thisDate); 
        System.out.println("----------------------------"); 
        System.out.println("After applying formating :");
        String strDateOutput = changeFormat.format(thisDate);
        System.out.println(strDateOutput);

    }

}

Eaxmple


If you really want to use a Date instead for a Calendar for comparison, this is the shortest piece of code you could use:

Calendar c = Calendar.getInstance();
Date d = new GregorianCalendar(c.get(Calendar.YEAR), 
                               c.get(Calendar.MONTH), 
                               c.get(Calendar.DAY_OF_MONTH)).getTime();

This way you make sure the hours/minute/second/millisecond values are blank.


Here's an inelegant way of doing it quick without additional dependencies.
You could just use java.sql.Date, which extends java.util.Date although for comparisons you will have to compare the Strings.

java.sql.Date dt1 = new java.sql.Date(System.currentTimeMillis());
String dt1Text = dt1.toString();
System.out.println("Current Date1 : " + dt1Text);

Thread.sleep(2000);

java.sql.Date dt2 = new java.sql.Date(System.currentTimeMillis());
String dt2Text = dt2.toString();
System.out.println("Current Date2 : " + dt2Text);

boolean dateResult = dt1.equals(dt2);
System.out.println("Date comparison is " + dateResult);
boolean stringResult = dt1Text.equals(dt2Text);
System.out.println("String comparison is " + stringResult);

Output:

Current Date1 : 2010-05-10
Current Date2 : 2010-05-10
Date comparison is false
String comparison is true


I was looking for the same solution and the following worked for me.

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.clear(Calendar.HOUR);
    calendar.clear(Calendar.MINUTE);
    calendar.clear(Calendar.SECOND);
    calendar.clear(Calendar.MILLISECOND);

    Date today = calendar.getTime();

Please note that I am using calendar.set(Calendar.HOUR_OF_DAY, 0) for HOUR_OF_DAY instead of using the clear method, because it is suggested in Calendar.clear method's javadocs as the following

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.

With the above posted solution I get output as

Wed Sep 11 00:00:00 EDT 2013

Using clear method for HOUR_OF_DAY resets hour at 12 when executing after 12PM or 00 when executing before 12PM.


You could always use apache commons' DateUtils class. It has the static method isSameDay() which "Checks if two date objects are on the same day ignoring time."

static boolean isSameDay(Date date1, Date date2) 

I did as follows and it worked:

calendar1.set(Calendar.HOUR_OF_DAY, 0);
calendar1.set(Calendar.AM_PM, 0);
calendar1.set(Calendar.HOUR, 0);
calendar1.set(Calendar.MINUTE, 0);
calendar1.set(Calendar.SECOND, 0);
calendar1.set(Calendar.MILLISECOND, 0);
Date date1 = calendar1.getTime();       // Convert it to date

Do this for other instances to which you want to compare. This logic worked for me; I had to compare the dates whether they are equal or not, but you can do different comparisons (before, after, equals, etc.)


The accepted answer by Jesper is correct but now outdated. The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them.

java.time

Instead use the java.time framework, built into Java 8 and later, back-ported to Java 6 & 7 and further adapted to Android.

Table of all date-time types in Java, both modern and legacy.png

If you truly do not care about time-of-day and time zones, use LocalDate in the java.time framework ().

LocalDate localDate = LocalDate.of( 2014 , 5 , 6 );

Today

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If you want to use the JVM’s current default time zone, make your intention clear by calling ZoneId.systemDefault(). If critical, confirm the zone with your user.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.
LocalDate today = LocalDate.now( z ) ;

Moment

If you care about specific moments, specific points on the timeline, do not use LocalDate. If you care about the date as seen through the wall-clock time used by the people of a certain region, do not use LocalDate.

Be aware that if you have any chance of needing to deal with other time zones or UTC, this is the wrong way to go. Naïve programmers tend to think they do not need time zones when in fact they do.

Strings

Call toString to generate a string in standard ISO 8601 format.

String output = localDate.toString();

2014-05-06

For other formats, search Stack Overflow for DateTimeFormatter class.

Joda-Time

Though now supplanted by java.time, you can use the similar LocalDate class in the Joda-Time library (the inspiration for java.time).

LocalDate localDate = new LocalDate( 2014, 5, 6 );