开发者

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开发者_JAVA技巧.


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();
cal.clear(Calendar.HOUR_OF_DAY);
cal.clear(Calendar.AM_PM);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);

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.

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.

edit - The answer above is from 2010; in Java 8, there is a new date and time API in the package java.time which is much more powerful and useful than the old java.util.Date and java.util.Calendar classes. Use the new date and time classes instead of the old ones.


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) 


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


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


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


You can get by this date:

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


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.


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.

Java program to get the current date without timestamp

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


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


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


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!
}


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


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.


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


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.


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


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

    }

}

Java program to get the current date without timestamp

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜