42

I have written some code to check two dates, a start date and an end date. If the end date is before the start date, it will give a prompt that says the end date is before start date.

I also want to add a check for if the start date is before today (today as in the day of which the user uses the application) How would I do this? ( Date checker code below, also all this is written for android if that has any bearing)

if (startYear > endYear) {
    fill = fill + 1;
    message = message + "End Date is Before Start Date" + "\n";
} else if (startMonth > endMonth && startYear >= endYear) {
    fill = fill + 1;
    message = message + "End Date is Before Start Date" + "\n";
} else if (startDay > endDay && startMonth >= endMonth && startYear >= endYear) {
    fill = fill + 1;
    message = message + "End Date is Before Start Date" + "\n";
}

12 Answers 12

154

Don't complicate it that much. Use this easy way. Import DateUtils java class and call the following methods which returns a boolean.

DateUtils.isSameDay(date1,date2);
DateUtils.isSameDay(calender1,calender2);
DateUtils.isToday(date1);

For more info refer this article DateUtils Java

5
  • 8
    This is easy, do this. Dec 14, 2015 at 19:38
  • 1
    Well, this may be easy, but it is important for people to understand that this is example code, seemingly without tests/coverage. It's presented here as some library you can pull in, but it's not different from other code snippets in other answers. It'd be better to pull in a library, such as Joda or Commons, as others mentioned, since you can rely their community maintenance. Sorry for picking at your answer, others may suffer the same problem. Please, please, use libraries where you can. If you have to copy code from the web, make sure to test and comprehend before going into production. Feb 6, 2017 at 9:35
  • 4
    I am getting error: The method isToday() is undefined for the type DateUtils.
    – learner
    Jun 2, 2018 at 9:36
  • 4
    @learner this method is only in Android version of DateUtils. For "desktop" JDK use DateUtils.isSameDay(someday, new Date()); Jul 11, 2018 at 8:37
  • I believe this is from apache commons lang Aug 27, 2019 at 17:26
46

Does this help?

Calendar c = Calendar.getInstance();

// set the calendar to start of today
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);

// and get that as a Date
Date today = c.getTime();

// or as a timestamp in milliseconds
long todayInMillis = c.getTimeInMillis();

// user-specified date which you are testing
// let's say the components come from a form or something
int year = 2011;
int month = 5;
int dayOfMonth = 20;

// reuse the calendar to set user specified date
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);

// and get that as a Date
Date dateSpecified = c.getTime();

// test your condition
if (dateSpecified.before(today)) {
  System.err.println("Date specified [" + dateSpecified + "] is before today [" + today + "]");
} else {
  System.err.println("Date specified [" + dateSpecified + "] is NOT before today [" + today + "]");
}
7
  • 1
    Shouldn't millis be also reset to zero at the beginning? Oct 8, 2012 at 7:51
  • 2
    Use Joda Time's DateMidnight and you don't need to reset anything.
    – martin
    Oct 15, 2012 at 10:51
  • Milliseconds alse need reset c.set(Calendar.MILLISECOND, 0); f you do not, there will be problems if you compare the dates the same day.
    – DragonT
    Feb 3, 2014 at 19:41
  • 2
    Using Calendar. HOUR is wrong, since it doesn't reset the AM/PM property, thus if the current time is 13 PM the resulting hour would be 12 PM. Use Calendar. HOUR_OF_DAY instead.
    – mgaido
    Jul 9, 2015 at 10:25
  • 1
    Update: These terrible date-time classes are now supplanted by the modern java.time classes defined in JSR 310. Jan 16, 2021 at 0:00
13

Using pure Java:

public static boolean isToday(Date date){
        Calendar today = Calendar.getInstance();
        Calendar specifiedDate  = Calendar.getInstance();
        specifiedDate.setTime(date);

        return today.get(Calendar.DAY_OF_MONTH) == specifiedDate.get(Calendar.DAY_OF_MONTH)
                &&  today.get(Calendar.MONTH) == specifiedDate.get(Calendar.MONTH)
                &&  today.get(Calendar.YEAR) == specifiedDate.get(Calendar.YEAR);
    }
11

tl;dr

LocalDate
.parse( "2021-01-23" )
.isBefore(
    LocalDate.now(
        ZoneId.of( "Africa/Tunis" ) 
    )
)

… or:

try 
{
    org.threeten.extra.LocalDateRange range =         
        LocalDateRange.of( 
            LocalDate.of( "2021-01-23" ) ,
            LocalDate.of( "2021-02-21" )
        )
    ;
    if( range.isAfter( 
        LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
    ) { … }
    else { … handle today being within or after the range. }
} catch ( java.time.DateTimeException e ) {
    // Handle error where end is before start.
}

Details

The other answers ignore the crucial issue of time zone.

The other answers use outmoded classes.

Avoid old date-time classes

The old date-time classes bundled with the earliest versions of Java are poorly designed, confusing, and troublesome. Avoid java.util.Date/.Calendar and related classes.

java.time

LocalDate

For date-only values, without time-of-day and without time zone, use the LocalDate class.

LocalDate start = LocalDate.of( 2016 , 1 , 1 );
LocalDate stop = start.plusWeeks( 1 );

Time Zone

Be aware that while LocalDate does not store a time zone, determining a date such as “today” requires a time zone. For any given moment, the date may vary around the world by time zone. For example, a new day dawns earlier in Paris than in Montréal. A moment after midnight in Paris is still “yesterday” in Montréal.

If all you have is an offset-from-UTC, use ZoneOffset. If you have a full time zone (continent/region), then use ZoneId. If you want UTC, use the handy constant ZoneOffset.UTC.

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

Comparing is easy with isEqual, isBefore, and isAfter methods.

boolean invalidInterval = stop.isBefore( start );

We can check to see if today is contained within this date range. In my logic shown here I use the Half-Open approach where the beginning is inclusive while the ending is exclusive. This approach is common in date-time work. So, for example, a week runs from a Monday going up to but not including the following Monday.

// Is today equal or after start (not before) AND today is before stop.
boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ) ;

LocalDateRange

If working extensively with such spans of time, consider adding the ThreeTen-Extra library to your project. This library extends the java.time framework, and is the proving ground for possible additions to java.time.

ThreeTen-Extra includes an LocalDateRange class with handy methods such as abuts, contains, encloses, overlaps, and so on.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

2
  • Too wordy. Answer buried in middle. Prefer answer at top and expound if you want.
    – Sun
    Jan 15, 2021 at 23:53
  • @Sun I added a “tl;dr” section up top. Thanks. Jan 16, 2021 at 0:15
9

Android already has a dedicated class for this. Check DateUtils.isToday(long when)

1
  • 2
    Perfect and simple. Thanks!
    – rjr-apps
    Sep 18, 2017 at 19:08
5

Using Joda Time this can be simplified to:

DateMidnight startDate = new DateMidnight(startYear, startMonth, startDay);
if (startDate.isBeforeNow())
{
    // startDate is before now
    // do something...
}
3
  • This is now Deprecated!
    – User3
    Feb 24, 2015 at 8:10
  • Also be very careful in the Month Argument - Joda's is in range 1-12 and Java has range 0-11. Can throw an IllegalArgument exception if the month is January and passed from Java. Although it's not documented, it will throw org.joda.time.IllegalFieldValueException (a subclass of IllegalArgumentException) if the value is invalid.
    – Junaid
    Mar 16, 2015 at 5:14
  • Good hint, but IMO Joda's range is the correct one anyway. 0-11 never made sense to me.
    – martin
    Mar 17, 2015 at 7:31
5

to check if a date is today's date or not only check for dates not time included with that so make time 00:00:00 and use the code below

    Calendar c = Calendar.getInstance();

    // set the calendar to start of today
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);

    Date today = c.getTime();

    // or as a timestamp in milliseconds
    long todayInMillis = c.getTimeInMillis();


    int dayOfMonth = 24;
    int month = 4;
    int year =2013;

    // reuse the calendar to set user specified date
    c.set(Calendar.YEAR, year);
    c.set(Calendar.MONTH, month - 1);
    c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    // and get that as a Date
    Date dateSpecified = c.getTime();

    // test your condition
    if (dateSpecified.before(today)) {

        Log.v(" date is previou")
    } else if (dateSpecified.equal(today)) {

        Log.v(" date is today ")
    } 
             else if (dateSpecified.after(today)) {

        Log.v(" date is future date ")
    } 

Hope it will help....

2
    boolean isBeforeToday(Date d) {
        Date today = new Date();
        today.setHours(0);
        today.setMinutes(0);
        today.setSeconds(0);
        return d.before(today);
    }
0
1

I assume you are using integers to represent your year, month, and day? If you want to remain consistent, use the Date methods.

Calendar cal = new Calendar();
int currentYear, currentMonth, currentDay; 
currentYear = cal.get(Calendar.YEAR); 
currentMonth = cal.get(Calendar.MONTH); 
currentDay = cal.get(Calendar.DAY_OF_WEEK);

     if(startYear < currentYear)
                {
                    message = message + "Start Date is Before Today" + "\n";
                }
            else if(startMonth < currentMonth && startYear <= currentYear)
                    {
                        message = message + "Start Date is Before Today" + "\n";
                    }
            else if(startDay < currentDay && startMonth <= currentMonth && startYear <= currentYear)
                        {
                            message = message + "Start Date is Before Today" + "\n";
                        }
1

another way to do this operation:

public class TimeUtils {

    /**
     * @param timestamp
     * @return
     */
    public static boolean isToday(long timestamp) {
        Calendar now = Calendar.getInstance();
        Calendar timeToCheck = Calendar.getInstance();
        timeToCheck.setTimeInMillis(timestamp);
        return (now.get(Calendar.YEAR) == timeToCheck.get(Calendar.YEAR)
                && now.get(Calendar.DAY_OF_YEAR) == timeToCheck.get(Calendar.DAY_OF_YEAR));
    }

}
0

Try this:

public static boolean isToday(Date date)
{
    return org.apache.commons.lang3.time.DateUtils.isSameDay(Calendar.getInstance().getTime(),date);
}
-1
public static boolean itIsToday(long date){
    boolean result = false;
    try{
        Calendar calendarData = Calendar.getInstance();
        calendarData.setTimeInMillis(date);
        calendarData.set(Calendar.HOUR_OF_DAY, 0);
        calendarData.set(Calendar.MINUTE, 0);
        calendarData.set(Calendar.SECOND, 0);
        calendarData.set(Calendar.MILLISECOND, 0);

        Calendar calendarToday = Calendar.getInstance();
        calendarToday.setTimeInMillis(System.currentTimeMillis());
        calendarToday.set(Calendar.HOUR_OF_DAY, 0);
        calendarToday.set(Calendar.MINUTE, 0);
        calendarToday.set(Calendar.SECOND, 0);
        calendarToday.set(Calendar.MILLISECOND, 0);

        if(calendarToday.getTimeInMillis() == calendarData.getTimeInMillis()) {
            result = true;
        }
    }catch (Exception exception){
        Log.e(TAG, exception);
    }
    return result;
}
1
  • 2
    These classes became legacy years ago, with the adoption of JSR 310. Suggesting their use in 2019 is poor advice. Use only java.time classes instead. Sep 6, 2019 at 2:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.