简体   繁体   中英

How to count that 24 Hours passed or not

I am facing a problem that I am saving the current device time in shared preferences behind a button click event. Eg: 11:05 am for the date(27-08-2015). After that when the user come to the same activity I have to change the layout file for the next 24 hours till (11:05 am for the date 28-08-2015) as per the project requirements. But I am facing the problem that how can I get that if 24 hours has been passed or not from the time of button click which was 11:05 am in this case. Any sort of help will be highly appreciated. Thank You.

If you want "24 hours later", use pure UTC time. Simplest is to use the raw millis.

// Save current time
long savedMillis = System.currentTimeMillis();

// Check time elapsed
if (System.currentTimeMillis() >= savedMillis + 24 * 60 * 60 * 1000) {
    // time has elapsed
}

If you want "after same time of day tomorrow", you have to either remember the timezone, or simply convert to un-zoned text.

SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

// Save current time
String savedTime = df.format(new Date()); // Applies local time zone 1

// Check time elapsed
Calendar cal = Calendar.getInstance();
cal.setTime(df.parse(savedTime)); // Applies local time zone 2
cal.add(Calendar.DAY_OF_MONTH, 1); // Adjusts for DST in local time zone 2
if (System.currentTimeMillis() >= cal.getTimeInMillis()) {
    // time has elapsed
}

Explanation

new Date() returns an instant in UTC time.
df.format returns text representation of that instant in the current default timezone , ie the timezone in effect for the JVM at the time the call is made (or rather when the SimpleDateFormat was created).

Later on, df.parse will parse that text back into an instant in UTC time, again using the current default timezone , but that may be a different timezone than used when df.format was called.
cal.setTime updates the Calendar to the instant in UTC time.
cal.add updates the Calendar to the same time 1 day later, adjusting for DST in the current default timezone , if needed.
cal.getTimeInMillis() is the UTC millis of the same time of day, 1 day after the saved time, in local time zone.

You usually compare times in milliseconds. Just check if the difference between the two times is bigger than 24*60*60*1000

If you want a safer comparison, use Androids Calendar . It checks for several things like timezones etc.

whenever the user returns just compare the current time with the one you saved in shared preferences. if the difference is 24h or more do whatever you wanted to do.

it also would be good to know in which environment / programming language you try to do this

You could use something like this:

 new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();

- http://developer.android.com/reference/android/os/CountDownTimer.html

But I think Mamata is right, especially if it is going to be every day.

Have a boolean value hasDayPassed that is set false when a new currentTime is set and then when the currentTime is compared to the newer time is true if they match.

Good luck

There are two cases:

  • the first is no timezone considered: here you can do in several ways,

the first i think at is:

//DateFormat is used formatting the Date with the sintax you like
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();
//save date in SharedPreferences using
String dateString = df.format(today);
sp.putString("date", dateString);

and when you have to get it back:

DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date;
if(preferences.contains("date")){
    String dateString = preferences.getString("date", "");
    if(dateString != ""){
        date = df.parse(dateString);
        if(new Date() >= date.addDays(1)){
            //a day is passed
        } else{
            //not passed
        }
    }else{
        //case date wrongly stored
    }
} else{
    //no date stored
}
  • if you have to consider timezones, add in sharedPref an int representing the +/- hours in timezone, using TimeZone class. Than when you get it back you have to compare the two timezones and add/subtract the difference from the new Date.

Save time in preferences:

Editor editor=mSharedPreferences.edit(); //mSharedPreferences is instance of your SharedPreferences
editor.putLong("time",System.currentTimeMillis());
editor.commit();

Check whenever you want to:

if(System.currentTimeMillis()-mSharedPreferences.getLong("time",0)<24*60*60*1000){
//with in a day
}else{
//greater than a day
}

PS .: It doesn't consider timezone though.

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