Best way to compare dates in Android

I am trying to compare a date in String format with the current date. This is how I did it (not tested, but should work), but using outdated methods. Any good suggestion for an alternative? Thank.

PS I really hate working with dates in Java. There are so many ways to do the same thing that you are really not sure which one is right, so my question is 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; } 
+75
java android datetime
May 27 '12 at 14:55
source share
14 answers

Your code can 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; } 
+167
May 27 '12 at 2:58 p.m.
source share
— -

You can use CompareTo ()

The CompareTo method should return a negative number if the current object is smaller than the other object, a positive number if the current object is larger than the 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 "); } 
+14
May 23 '16 at 13:28
source share

You can directly create Calendar from Date :

 Calendar validDate = new GregorianCalendar(); validDate.setTime(strDate); if (Calendar.getInstance().after(validDate)) { catalog_outdated = 1; } 
+9
May 27 '12 at 14:59
source share

Please note that before the code works, the correct format ("dd / MM / yyyy"). “mm” means “thumbnails”!

 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; } 
+9
May 13, '13 at 21:35
source share
 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 .. and you can also check for and equal with date.before and date.equal ..

+4
Jun 10 '14 at 7:55
source share
 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 } 
+4
Apr 6 '17 at 9:10
source share
 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 with that presented by this calendar.

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

+2
Sep 30 '13 at 11:57
source share

convert the date to Calendar and do 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; } 
+1
May 27 '12 at 2:59 p.m.
source share

You can 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 can use today.getTime() to extract the value and compare.

+1
May 27 '12 at 15:04
source share

Sometimes we need to make a list with dates, for example

today with an hour

yesterday with yesterday

other days from 06/23/2017

To do this, we need to compare the 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; } } 

You can also check this example on GitHub , and this post .

+1
Jun 23 '17 at 9:53 on
source share

Time for a 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 just ran this code, the output was:

The catalog is out of date

Since this is never the same date in all time zones, LocalDate.now explicit time zone for LocalDate.now . If you want the catalog to expire simultaneously in all time zones, you can ZoneOffset.UTC as long as you inform users that you are using UTC.

I am using java.time, a modern Java date and time API. The Calendar , SimpleDateFormat and Date date and time classes you use are poorly designed and, fortunately, are deprecated. Also, despite the name, Date does not represent a date, but a point in time. One consequence of this is that, although today is February 15, 2019, the newly created Date object is already after (therefore not equal to) the Date object from parsing 15/02/2019 . This confuses some. In contrast, the current LocalDate is a date without a time of day (and without a time zone), so the two LocalDate representing today's date will always be equal.

Question: Can I use java.time on Android?

Yes, java.time works great on old and new Android devices. It just requires at least Java 6 .

  • Java 8 and later, as well as newer Android devices (starting at API level 26) have a modern API built in.
  • In Java 6 and 7, get ThreeTen Backport, the backport of modern classes (ThreeTen for JSR 310; see the links below).
  • On (older) Android, use the Android version of ThreeTen Backport. It is called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with org.threeten.bp .

communication

+1
Feb 15 '19 at 14:49
source share

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

0
May 27 '12 at 15:01
source share

Joda time

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

Localdate

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

Timezone

Getting the current date depends on the time zone. In Paris, a new date begins in front of Montreal. Specify the desired time zone, and not depend on the default JVM value.

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 ); 
0
Jun 11 '14 at 8:06
source share
 try { SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); String str1 = "9/10/2015"; Date date1 = formatter.parse(str1); String str2 = "10/10/2015"; Date date2 = formatter.parse(str2); if (date1.compareTo(date2) < 0) { System.out.println("date2 is Greater than my date1"); } } catch (ParseException e1) { e1.printStackTrace(); } 
0
Apr 02 '19 at 7:45
source share



All Articles