使用Calendar对象读取和写入SharedPreferences的当前日期

时间:2013-03-07 12:34:49

标签: android date calendar sharedpreferences

我想在应用程序中写入首选项更新数据的最后日期。所以我确实喜欢这个

Calendar cal = Calendar.getInstance();
SharedPreferences settings = getSharedPreferences("OrderOnline", 0);
Long updDate = settings.getLong("lastupdate", 0);
Long currdate= cal.getTimeInMillis();
if (!(updDate == currdate)) {
Log.d("AMainActivity", "updDate = " + updDate + "; currdate = " + currdate);
...
Editor ed = settings.edit();
        ed.putLong("lastupdate", currdate);
        ed.commit();
}

但这不是我想要的。如何在SharedPreferences中读取和写入当前日期?我不想使用任何已弃用的对象。谢谢。

P.S。我确实想要首选项中的当前日期,而不是秒。现在(!(updDate == currdate))将始终为True。

UPD 我添加了这个

Calendar cal = Calendar.getInstance();
SharedPreferences settings = getSharedPreferences("OrderOnline", 0);
Long updDate = settings.getLong("lastupdate", 0)/ MILLIS_PER_DAY;
Long currdate= cal.getTimeInMillis()/ MILLIS_PER_DAY;
if (!(updDate == currdate)) {
  Log.d("AMainActivity", "updDate = " + updDate + "; currdate = " + currdate);


...
  Editor ed = settings.edit();
        ed.putLong("lastupdate", currdate);
        ed.commit();
}

进入{}这是结果

03-07 13:10:15.031: D/AMainActivity(9291): updDate = 15771; currdate = 15771

有些东西不起作用。

1 个答案:

答案 0 :(得分:2)

用它来比较天数而不是毫秒:

long MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
long updDate = settings.getLong("lastupdate", 0) / MILLIS_PER_DAY;
long currdate= System.currentTimeMillis() / MILLIS_PER_DAY;

if (!(upDate == currDate)) ...

一个短的单元测试来证明事物: 这写道“现在这就是我的想法”和“看,它有用”。

public void test() throws InterruptedException {
    long MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
    long updDate = 0 / MILLIS_PER_DAY;
    long currDate = System.currentTimeMillis() / MILLIS_PER_DAY;

    if (!(updDate == currDate)) {
        System.out.println("now that's what I thought");
    }

    updDate = System.currentTimeMillis() / MILLIS_PER_DAY;
    Thread.sleep(5000);
    currDate = System.currentTimeMillis() / MILLIS_PER_DAY;

    if (!(updDate == currDate)) {
        System.out.println("now that's STRANGE");
    } else {
        System.out.println("see, it works");
    }
}