122

I am trying to compare a date in a String format to the current date. This is how I did it (haven't tested, but should work), but am using deprecated methods. Any good suggestion for an alternative? Thanks.

P.S. I really hate doing Date stuff in Java. There are so many ways to do the same thing, that you really aren't sure which one is the correct one, hence my question here.

String valid_until = "1/1/1990";

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
Date strDate = sdf.parse(valid_until);

int year = strDate.getYear(); // this is deprecated
int month = strDate.getMonth() // this is deprecated
int day = strDate.getDay(); // this is deprecated       

Calendar validDate = Calendar.getInstance();
validDate.set(year, month, day);

Calendar currentDate = Calendar.getInstance();

if (currentDate.after(validDate)) {
    catalog_outdated = 1;
}
nunos
  • 20,479
  • 50
  • 119
  • 154
  • 5
    In 2018 the best way doesn’t involve `Calendar`, `SimpleDateFormat`, `Date` or any of the other long outdated Java date and time classes. Instead use [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Jun 15 '18 at 09:33

16 Answers16

252

Your code could be reduced to

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
    catalog_outdated = 1;
}

or

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (System.currentTimeMillis() > strDate.getTime()) {
    catalog_outdated = 1;
}
Community
  • 1
  • 1
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
27

You can use compareTo()

CompareTo method must return negative number if current object is less than other object, positive number if current object is greater than other object and zero if both objects are equal to each other.

// Get Current Date Time
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm aa");
String getCurrentDateTime = sdf.format(c.getTime());
String getMyTime="05/19/2016 09:45 PM ";
Log.d("getCurrentDateTime",getCurrentDateTime); 
// getCurrentDateTime: 05/23/2016 18:49 PM

if (getCurrentDateTime.compareTo(getMyTime) < 0)
{

}
else
{
 Log.d("Return","getMyTime older than getCurrentDateTime "); 
}
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
  • 1
    FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. Most of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android (<26) in [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Feb 15 '19 at 20:03
12

You can directly create a Calendar from a Date:

Calendar validDate = new GregorianCalendar();
validDate.setTime(strDate);
if (Calendar.getInstance().after(validDate)) {
    catalog_outdated = 1;
}
assylias
  • 321,522
  • 82
  • 660
  • 783
11

Note that the right format is ("dd/MM/yyyy") before the code works. "mm" means minuts !

String valid_until = "01/07/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = null;
try {
    strDate = sdf.parse(valid_until);
} catch (ParseException e) {
    e.printStackTrace();
}
if (new Date().after(strDate)) {
    catalog_outdated = 1;
}
AlexB
  • 7,302
  • 12
  • 56
  • 74
Rocologo
  • 574
  • 5
  • 11
10
Calendar toDayCalendar = Calendar.getInstance();
Date date1 = toDayCalendar.getTime();


Calendar tomorrowCalendar = Calendar.getInstance();
tomorrowCalendar.add(Calendar.DAY_OF_MONTH,1);
Date date2 = tomorrowCalendar.getTime();

// date1 is a present date and date2 is tomorrow date

if ( date1.compareTo(date2) < 0 ) {

  //  0 comes when two date are same,
  //  1 comes when date1 is higher then date2
  // -1 comes when date1 is lower then date2

 }
Siva krishna
  • 187
  • 2
  • 8
  • FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. Most of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android (<26) in [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Feb 15 '19 at 20:02
9
String date = "03/26/2012 11:00:00";
String dateafter = "03/26/2012 11:59:00";
SimpleDateFormat dateFormat = new SimpleDateFormat(
        "MM/dd/yyyy hh:mm:ss");
Date convertedDate = new Date();
Date convertedDate2 = new Date();
try {
    convertedDate = dateFormat.parse(date);
    convertedDate2 = dateFormat.parse(dateafter);
    if (convertedDate2.after(convertedDate)) {
        txtView.setText("true");
    } else {
        txtView.setText("false");
    }
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

It returns true. You can also check before and equal with the help of date.before and date.equal.

BSMP
  • 4,596
  • 8
  • 33
  • 44
Dilavar Malek
  • 1,157
  • 11
  • 18
6

convert the date to Calendar and make your calculations there. :)

Calendar cal = Calendar.getInstance();
cal.setTime(date);

int year = cal.get(Calendar.YEAR);
int month = cal.geT(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH); //same as cal.get(Calendar.DATE)

Or:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);

if (strDate.after(new Date()) {
    catalog_outdated = 1;
}
Nuno Gonçalves
  • 6,202
  • 7
  • 46
  • 66
5

In Kotlin it is quite simple with build-in functions after() or before() to compare two time objects:

expirationTime.after(Date())
flame3
  • 2,812
  • 1
  • 24
  • 32
3

Time for the modern answer.

java.time and ThreeTenABP

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
    String validUntil = "1/1/1990";
    LocalDate validDate = LocalDate.parse(validUntil, dateFormatter);
    LocalDate currentDate = LocalDate.now(ZoneId.of("Pacific/Efate"));
    if (currentDate.isAfter(validDate)) {
        System.out.println("Catalog is outdated");
    }

When I ran this code just now, the output was:

Catalog is outdated

Since it is never the same date in all times zones, give explicit time zone to LocalDate.now. If you want the catalog to expire at the same time in all time zones, you may give ZoneOffset.UTC as long as you inform you users that you are using UTC.

I am using java.time, the modern Java date and time API. The date-time classes that you used, Calendar, SimpleDateFormat and Date, are all poorly designed and fortunately long outdated. Also despite the name a Date doesn’t represent a date, but a point in time. One consequence of this is: even though today is February 15, 2019, a newly created Date object is already after (so not equal to) a Date object from parsing 15/02/2019. This confuses some. Contrary to this the modern LocalDate is a date without time of day (and without time zone), so two LocalDates representing today’s date will always be equal.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
2
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();

Date date1 = dateFormat.parse("2013-01-01");
Date date2 = dateFormat.parse("2013-01-02");

calendar1.setTime(date1);
calendar2.setTime(date2);

System.out.println("Compare Result : " + calendar2.compareTo(calendar1));
System.out.println("Compare Result : " + calendar1.compareTo(calendar2));

Compares the time represented by this Calendar to that represented by the given Calendar.

Returns 0 if the times of the two Calendars are equal, -1 if the time of this Calendar is before the other one, 1 if the time of this Calendar is after the other one.

Kirit Vaghela
  • 12,572
  • 4
  • 76
  • 80
2

Update: The Joda-Time library is now in maintenance-mode, and recommends migrating to the java.time framework that succeeds it. See the Answer by Ole V.V..


Joda-Time

The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8.

LocalDate

If you want date-only without time-of-day, then use the LocalDate class.

Time Zone

Getting the current date depends on the time zone. A new date rolls over in Paris before Montréal. Specify the desired time zone rather than depend on the JVM's default.

Example in Joda-Time 2.3.

DateTimeFormat formatter = DateTimeFormat.forPattern( "d/M/yyyy" );
LocalDate localDate = formatter.parseLocalDate( "1/1/1990" );
boolean outdated = LocalDate.now( DateTimeZone.UTC ).isAfter( localDate );
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
2

Sometimes we need to do a list with dates, like

today with hour

yesterday with yesterday

other days with 23/06/2017

To make this we need to compare current time with our data.

Public class DateUtil {

    Public static int getDateDayOfMonth (Date date) {
        Calendar calendar = Calendar.getInstance ();
        Calendar.setTime (date);
        Return calendar.get (Calendar.DAY_OF_MONTH);
    }

    Public static int getCurrentDayOfMonth () {
        Calendar calendar = Calendar.getInstance ();
        Return calendar.get (Calendar.DAY_OF_MONTH);
    }

    Public static String convertMillisSecondsToHourString (long millisSecond) {
        Date date = new Date (millisSecond);
        Format formatter = new SimpleDateFormat ("HH: mm");
        Return formatter.format (date);
    }

    Public static String convertMillisSecondsToDateString (long millisSecond) {
        Date date = new Date (millisSecond);
        Format formatter = new SimpleDateFormat ("dd / MM / yyyy");
        Return formatter.format (date);
    }

    Public static long convertToMillisSecond (Date date) {
        Return date.getTime ();
    }

    Public static String compare (String stringData, String yesterday) {

        String result = "";

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss");
        Date date = null;

        Try {
            Date = simpleDateFormat.parse (stringData);
        } Catch (ParseException e) {
            E.printStackTrace ();
        }

        Long millisSecond = convertToMillisSecond (date);
        Long currencyMillisSecond = System.currentTimeMillis ();

        If (currencyMillisSecond> millisSecond) {
            Long diff = currencyMillisSecond - millisSecond;
            Long day = 86400000L;

            If (diff <day && getCurrentDayOfMonth () == getDateDayOfMonth (date)) {
                Result = convertMillisSecondsToHourString (millisSecond);

            } Else if (diff <(day * 2) && getCurrentDayOfMonth () -1 == getDateDayOfMonth (date)) {
                Result = yesterday;
            } Else {
                Result = convertMillisSecondsToDateString (millisSecond);
            }
        }

        Return result;
    }
}

Also you can check this example in GitHub and this post.

Cabezas
  • 9,329
  • 7
  • 67
  • 69
1

You could try this

Calendar today = Calendar.getInstance (); 
today.add(Calendar.DAY_OF_YEAR, 0); 
today.set(Calendar.HOUR_OF_DAY, hrs); 
today.set(Calendar.MINUTE, mins ); 
today.set(Calendar.SECOND, 0); 

and you could use today.getTime() to retrieve value and compare.

Anurag Ramdasan
  • 4,189
  • 4
  • 31
  • 53
0

You can use validDate.setTime(strDate) Have a look at the javadoc at http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html

phlogratos
  • 13,234
  • 1
  • 32
  • 37
0
SimpleDateFormat sdf=new SimpleDateFormat("d/MM/yyyy");
Date date=null;
Date date1=null;
try {
       date=sdf.parse(startDate);
       date1=sdf.parse(endDate);
    }  catch (ParseException e) {
              e.printStackTrace();
    }
if (date1.after(date) && date1.equals(date)) {
//..do your work..//
}
kartik_g
  • 21
  • 2
0

Kotlin supports operators overloading

In Kotlin you can easily compare dates with compare operators. Because Kotlin already support operators overloading. So to compare date objects :

firstDate: Date = // your first date
secondDate: Date = // your second date

if(firstDate < secondDate){
// fist date is before second date
}

and if you're using calendar objects, you can easily compare like this:

if(cal1.time < cal2.time){
// cal1 date is before cal2 date
}
Khaled Qasem
  • 879
  • 7
  • 20