Fodis Fodis - 9 months ago 76
Java Question

Check new day using Shared preferences

I have created an app. I have Put a button in my app. When I click on the button the click time is saved to shared preferences.

private void saveClickTime() {
String str = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
SharedPreferences.Editor localEditor = this.sp.edit();
localEditor.putString("mTime", str);

Now I want to create a method
when a new day starts. Like today is 3rd October. On 12.00 Pm 4th October will starts. I want that when a new days starts the method will start.

private boolean isTimeToClick() {
SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
// here I have to call the method but I don't know what should I use. can anyone help me?
catch (Exception localException) {}
return false;

Answer Source

You can store time in milliseconds and retrieve it to create a date instance from shared preferences and compare the dates.

private void saveClickTime() {
    sp.edit().putLong("mTime", System.currentTimeMillis()).apply();

private boolean isTimeToClick() {
    Date oldDate = new Date(sp.getLong("mTime", System.currentTimeMillis()));
    GregorianCalendar oldCalendar = new GregorianCalendar();
    Calendar newCalendar = new GregorianCalendar();
    return newCalendar.get(Calendar.DATE) != oldCalendar.get(Calendar.DATE) ||
            newCalendar.get(Calendar.MONTH) != oldCalendar.get(Calendar.MONTH) ||
            newCalendar.get(Calendar.YEAR) != oldCalendar.get(Calendar.YEAR);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download