How can I tell if DateTime.Now() is on a day AFTER a different DateTime

后端 未结 5 1495
庸人自扰
庸人自扰 2021-01-23 17:43

I\'m running this on flutter, but I guess this could be a more general issue.

I am saving a DateTime in the preferences. I want to be able to then tell if DateTime

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-23 18:17

    I would compute the difference between midnight of the day of the last timestamp and midnight of the current timestamp. That is, consider only the date portion of a DateTime and ignore the time.

    DateTime date(DateTime dateTime) =>
        DateTime(dateTime.year, dateTime.month, dateTime.day);
    
    // Intentionally check for a positive difference in hours instead of days
    // so we don't need to worry about 23-hour days from DST.  Any non-zero
    // number of hours here means a difference of at least a "day".
    if (date(DateTime.now()).difference(date(lastDailyCheck)).inHours > 0) {
      // "One day" after.
    }
    

    If you're using UTC timestamps and don't care about when midnight is in whatever the local time is, the comparison could more intuitively use .inDays >= 1.

提交回复
热议问题