Home > Enterprise >  How can I check if 24 hours have passed between two dates in kotlin?
How can I check if 24 hours have passed between two dates in kotlin?

Time:12-04

I need to check if 24 hours have passed between two dates. If 24 hours have passed, I will update the data in my room database, if not, I will not. How can I do that. I thought about keeping a date with shared preferences and comparing that date with the current date, but I don't know how to do that.

CodePudding user response:

You need to check that the different between the date stored in shared pref as an Long and the current date are bigger than or equal the value of 1 day in millis

var isDayPassed = (System.currentTimeMillis() - date) >= TimeUnit.DAYS.toMillis(1)

Note: Make sure to import TimeUnit using import java.util.concurrent.TimeUnit

CodePudding user response:

Here is an example of how you could check if 24 hours have passed between two dates in Android using the java.util.Date class:

// Get the current date and time Date currentDate = new Date();

// Get the date and time from the shared preferences
// Replace "dateKey" with the key for the date in the shared preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
long savedDateMillis = preferences.getLong("dateKey", 0);
Date savedDate = new Date(savedDateMillis);

// Calculate the difference between the current date and the saved date in milliseconds
long timeDifference = currentDate.getTime() - savedDate.getTime();

// Convert the time difference from milliseconds to hours
long timeDifferenceHours = TimeUnit.MILLISECONDS.toHours(timeDifference);

// Check if 24 hours have passed
if (timeDifferenceHours >= 24) {
  // 24 hours or more have passed, so update the data in the room database
  // ...

  // Save the current date and time in the shared preferences
  SharedPreferences.Editor editor = preferences.edit();
  editor.putLong("dateKey", currentDate.getTime());
  editor.apply();
} else {
  // Less than 24 hours have passed, so do not update the data in the room database
  // ...
}

In this code, we use the java.util.Date class to get the current date and time and the date and time from the shared preferences. We then calculate the difference between the two dates in milliseconds and convert it to hours. Finally, we check if 24 hours or more have passed, and if so, we update the data in the room database and save the current date and time in the shared preferences.

I hope this helps! Let me know if you have any questions.

  • Related