Domanda

I've been trying this from a long time.
I'm having today's date and I want to compare it with specific date.

But when I set particular date like this, it gives me wrong output:

    Calendar cal;
    SimpleDateFormat dateformatter;
    String currentdate;
    cal = Calendar.getInstance();
    dateformatter = new SimpleDateFormat("yyyy-MM-dd");

    //Getting today's date
    currentdate = dateformatter.format(cal.getTime());
    Log.i(Class_Tag, "current = " + currentdate);

    //Setting specific date
    Date start = cal.getTime();
    cal.set(2012, 06, 20);
    Date end = cal.getTime();
    Log.i(Class_Tag, "end = " + dateformatter.format(end));

    long diff = end.getDate() - start.getDate();
    Log.i(Class_Tag, "diff : " + diff);

    long diff1 = end.getMonth() - start.getMonth();
    Log.i(Class_Tag, "diff mnth : " + diff1);

    long diff2 = end.getYear() - start.getYear();
    Log.i(Class_Tag, "diff yr : " + diff2);

    if (start.compareTo(end) == 0) {
        Log.i(Class_Tag, "EQUAL");
    } else if (start.compareTo(end) < 0) {
        Log.i(Class_Tag, "end b4 start, delete");
    } else {
        Log.i(Class_Tag, "start b4 end, do nothing");

OUTPUT:

current = 2012-06-20
end = 2012-07-20 ////WHY it is showing month as '7' when I've set it to '6'?
diff : 0
diff mnth : 1 //Because of the wrong month in end date, this comes 1 instead of 0
diff yr : 0
end b4 start, delete //this also is not correct

I've tried several solutions, but no gains.

My only objective is to get whether that particular date has passed today's date or not.

Any help appreciated.


Edit

in the following code snippet,

//Setting specific date
    Date start = cal.getTime();
    cal.set(2012, 06, 20);
    Date end = cal.getTime();

If I set cal.set(2012, 06, 20); to cal.set(2012, 05, 20);, the month diff. comes out to 0.

This implies that month in particular date is getting incremented by '1', but WHY?

È stato utile?

Soluzione

FYI, A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.

You can check read more about Date here and more about SimpleDateFormat.

Update:

One more thing about getMonth() => Its deprecated, instead Calendar.get(Calendar.MONTH), check here.

Altri suggerimenti

Try this;

Calendar cal = Calendar.getInstance();

long dateNowMillis = cal.getTimeInMillis();

cal.set(2013, 1, 23);

long specDate = cal.getTimeInMillis();

if(dateNowMillis > specDate)
{
    System.out.println("Passed");
}
else if(dateNowMillis == specDate)
{
    System.out.println("Now");
}
else
{
    System.out.println("Not passed");
}

@GAMA Like this you get :

yourDate.setDate(yourDate.getDate() - daysToSubtract);

Hope it Helps.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top