Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare current date with selected date in android with java

Tags:

android

I am taking current date using the code like below

long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);

And I am selecting date using

CalendarView cal.setOnDateChangeListener(new OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth)

String s = +year + " : " + (month + 1) + " : " +dayOfMonth ;

and passing it on next activity as--

Intent in = new Intent(MainActivity.this, sec.class);
in.putExtra("TextBox", s.toString());
startActivity(in);

I want to check here if user selected previous date from current date then give a message and don't go on next activity.

like image 571
Soni Kumar Avatar asked Aug 01 '15 07:08

Soni Kumar


People also ask

How can I compare two date values in Java?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.

How do you check if a date is after another date in Java?

The after() method is used to check if a given date is after another given date. Return Value: true if and only if the instant represented by this Date object is strictly later than the instant represented by when; false otherwise.


1 Answers

Use SimpleDateFormat:

If your date is in 31/12/2014 format.

String my_date = "31/12/2014"

Then you need to convert it into SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(my_date);
if (new Date().after(strDate)) {
    your_date_is_outdated = true;
}
else{
    your_date_is_outdated = false;
}

or

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(my_date);
if (System.currentTimeMillis() > strDate.getTime()) {
    your_date_is_outdated = true;
}
else{
    your_date_is_outdated = false;
}
like image 147
Mohammad Arman Avatar answered Oct 28 '22 17:10

Mohammad Arman