Best way to compare dates in Android
JavaAndroidDatetimeJava Problem Overview
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;
}
Java Solutions
Solution 1 - Java
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;
}
Solution 2 - Java
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 ");
}
Solution 3 - Java
You can directly create a Calendar
from a Date
:
Calendar validDate = new GregorianCalendar();
validDate.setTime(strDate);
if (Calendar.getInstance().after(validDate)) {
catalog_outdated = 1;
}
Solution 4 - Java
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;
}
Solution 5 - Java
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
.
Solution 6 - Java
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
}
Solution 7 - Java
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;
}
Solution 8 - Java
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.
Solution 9 - Java
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 LocalDate
s 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
- Oracle tutorial: Date Time explaining how to use java.time.
- Java Specification Request (JSR) 310, where
java.time
was first described. - ThreeTen Backport project, the backport of
java.time
to Java 6 and 7 (ThreeTen for JSR-310). - ThreeTenABP, Android edition of ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Solution 10 - Java
In Kotlin it is quite simple with build-in functions after() or before() to compare two time objects:
expirationTime.after(Date())
Solution 11 - Java
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.
Solution 12 - Java
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 );
Solution 13 - Java
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;
}
}
Solution 14 - Java
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
Solution 15 - Java
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..//
}
Solution 16 - Java
> 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
}