Question

I want to implement a method to perform periodic updates

  public void periodicUpdate(int frequence){
        //frequence 1 daily, 2 monthly, 3 yearly
        switch(frequence){
            case 1:
                if(aDayIsExpired()){
                    update();
                }
                break;

            case 2:
                if(aMontyhIsExpired()){
                    update();
                }
                break;
            ...

        }

        default:
        if(aYearIsExpired()){
            update();
        }
        break;
        ...

    }

But I don't know how could I count a day, a month and a year expiration. I need something like

 GregorianCalendar startDate = new GregorianCalendar();

stored, and everytime app starts I should do a comparation with

GregorianCalendar now = new GregorianCalendar();

Unfortunately I don't know how to compare now and startDate to meet my problem and if this is the right way.

Was it helpful?

Solution

Depends on what your definition of "a year has passed" is. It could be 365 days, could be that you have the same value day/month field and just +1 in the year field.

If we assume a 365 day year, you could use

if((now.getTimeInMillis() - startDate.getTimeInMillis()) > 31556952000)
    return true;

for your "aYearHasPassed" method, 31556952000 being the amount of milliseconds in 365 days.

Just one way to skin the cat, might not meet your exact requirement.

OTHER TIPS

Store the date in SharedPreferences. When the app starts, load up the date and compare to the current date.

You can compare the two calendars by getting the milliseconds from the epoch by calling getTime() and doing the math. Or, you could create a clone of the saved calendar object, roll() it forward by the amount of time you want (7 days, a month, etc) and compare them using Calendar.compareTo(saved calendar)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top