开发者

Easiest way to compare dates

开发者 https://www.devze.com 2023-04-13 01:52 出处:网络
I\'ve seen numerous posts about Dates and comparing, but I\'m looking for something in perticular. Basically when this part of the app is opened I want it to save a date with shared preferences. (So

I've seen numerous posts about Dates and comparing, but I'm looking for something in perticular.

Basically when this part of the app is opened I want it to save a date with shared preferences. (So preferably it is a long, string or something of the sort that can be saved). When 4 days have passed since it has been opened it should have a graphical change. (It no longer uses the graphic that it ha开发者_JS百科d the previous 4 days) and it will do this again 2 more times. So what is the best way to compare a saved date/time to the current to determine if 4 days have passed

Preferably I would like to use something like this in some form

if(savedDate < 4Days){
//One image will be displayed during these 4 days
}
else if(savedDate <= 8Days){
//Another images shows for these 4 days
}

It just needs to know whether that alotted amount of time has passed or not. I hope I didn't make it too confusing. Any help is appreciated thanks.


Use System.currentTimeMillis

Save it in the shared preferances as long value and always compare it with a new measured currentTimeMillis until the difference would be > 4 * 24 * 60 * 60 * 1000


Maybe something like this:

Calendar now = Calendar.getInstance();
// Go back 4 days.
now.add(Calendar.DATE, -4);
Date fourDaysAgo = now.getTime();

if (savedDate.after(fourDaysAgo))
{
   // Show first image
}
else
{
    //Show second image.
}

If you don't want to show the second image after 8 days, then you'll need to add another condition but this should put you on the right lines, I think.


You may save the current time in milliseconds using System.currentTimeMillis() http://developer.android.com/reference/android/os/SystemClock.html.

long currentTimeMillis = System.currentTimeMillis();
long oneDayMillis = 24 * 3600 * 1000;

if((currentTimeMillis - savedTimeMillis) < (4 * oneDayMillis)){
  //One image will be displayed during these 4 days
}
else if((currentTimeMillis - savedTimeMillis) < (8 * oneDayMillis)){
 //Another images shows for these 4 days
}else{
 // do...
}

The basic date operation in the java.util.date like equals, after and before are done with a long who represents the time since the 1970-01-01 00:00:00. do not forget to consider the time zone :).

I hope this helps you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号