简体   繁体   中英

Android 30 Days From Todays Date

I need my application VIP feature to expire 30 days from today, I will store the current date in the application config. How will I check if the VIP feature has expired ? I don't mind if the user changed the clock back and the app works.

When user Activate a VIP features

mCurrentUser.setVip();
mCurrentUser.SaveInBackgroud();

// in want to also set StartDate and EndDate

Then to verify if the date saved in mCurrentUser endDate is igual to today

// set user to no VIP! like

mCurrentUser.setNoVip();
mCurrentUser.SaveInBackgroud();

You can get date after 30 days from given date by following method.

Calendar c = Calendar.getInstance();
    c.setTime(startDate);
    c.add(Calendar.DATE, 30);
Date expDate = c.getTime();

After that you can compare both dates.

if(startDate.after(expiate)){
   // Your time expired do your logic here.
}

if true then time is expired.

You should not store such information locally at all in this case. Instead, add field "activationDate" in Users table. Then do query for it and then do calculations locally.

If you want it to expire exactly on the second in 30d he started the vip, you can use this:

to start the timer:

SharedPreferences.editor editor1= getSharedPreferences("vipexpire", MODE_PRIVATE).edit();

                    editor1.putInt("starttime", (int) System.currentTimeMillis() / 1000);
                    editor1.apply();

in onCreate of your mainActivity, to check every time user opens app if the time is over:

SharedPreferences vipTimer= getSharedPreferences("vipexpire", MODE_PRIVATE);
int startTime= vipTimer.getInt("starttime", 0);
int currentTime = System.currentTimeMillis() / 1000;
int timeofVip= currentTime - startTime; //calculate the time of his VIP-being time
if (timeofVip>= 2592000)  //2592000 is 30 days in seconds
{
//30 days over, update user to non-vip
}

This method is also nice to have when storing the timestamp on a server or if you want to have an accurate countdown displayed in your app!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM