如果Date是第二天,请运行方法

时间:2016-03-12 14:20:12

标签: java android java.util.date

我想做这样的事情:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);

 int i = (int) (new Date().getTime()/1000);

   if(      ) // next day
     {
         mymethod();
     }
}

如果系统日期是新的一天,那么我想拨打mymethod()

3 个答案:

答案 0 :(得分:0)

建议使用Calendar类而不是Date。你可以检查一天过去是否这样:

  1. 在某些情况下,例如按钮单击,应用程序首先启动,在sharedPreferences中保存时间
  2. 检索该值并将其与当前时间进行比较 只是说明如何执行此操作:

    protected void onCreate(Bundle savedInstanceState){
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);
    
        Calendar c = Calendar.getInstance(); 
        int currentTimeSeconds = c.get(Calendar.SECOND);
    
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        int secondsPreviousDay = prefs.getInt("seconds", 0);
        if (secondsPreviousDay != 0){ //means there was an earlier set value from previously entering the activity
            //compare if more than 3600*24 = 86400 (1 day in seconds) had passed
            if (currentTimeSeconds - secondsPreviousDay > 86400){
                 mymethod();
            }
        }
        else {
            prefs.edit().putInt("seconds", currentTimeSeconds).apply();
        }
    }
    
  3. 在我的代码中,我假设您想要查看从您第一次开始此活动到第二次是否已过去一天。你可以根据自己的喜好调整这个,但我希望这个想法是可以理解的。

      

    我知道我可以将这两个人压缩成一个,但我只是希望它更清楚我追求的是什么。

答案 1 :(得分:0)

好主意!

在我的第一个活动中,我在onCreate中设置了类似的内容:

 Calendar c = Calendar.getInstance();
    int currentTimeSeconds = c.get(Calendar.SECOND);
    SharedPreferences share = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor edittime = share.edit();
    edittime.putInt("timevalue",currentTimeSeconds);
    edittime.commit();

并在onCreate:

中的另一个活动中使用您的代码
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    int secondsPreviousDay = prefs.getInt("seconds", 0);
    if (secondsPreviousDay != 0){ //means there was an earlier set value from previously entering the activity
        //compare if more than 3600*24 = 86400 (1 day in seconds) had passed
        if (currentTimeSeconds - secondsPreviousDay > 86400){
           // mymethod();
            mymethod();

        }
    }
    else {
        prefs.edit().putInt("seconds", currentTimeSeconds).apply();
    }
}

我很抱歉,但我还在学习

答案 2 :(得分:0)

新的一天是指午夜之后?所以你想检测日期是否与上次不同?

  @Override
  protected void onResume() {
     SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
     int lastTimeStarted = settings.getInt("last_time_started", -1);
     Calendar calendar = Calendar.getInstance();
     int today = calendar.get(Calendar.DAY_OF_YEAR);

    if (today != lastTimeStarted) {
      //startSomethingOnce();

      SharedPreferences.Editor editor = settings.edit();
      editor.putInt("last_time_started", today);
      editor.commit();
    }
  }