我如何判断DateTime.Now()是否在其他DateTime之后的一天 [英] How can I tell if DateTime.Now() is on a day AFTER a different DateTime

查看:283
本文介绍了我如何判断DateTime.Now()是否在其他DateTime之后的一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在忙碌地运行它,但我想这可能是一个更普遍的问题。

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

我在首选项中保存了DateTime。然后,我想知道 DateTime.now()是否在最后一次保存的DateTime后至少一天的上,即

I am saving a DateTime in the preferences. I want to be able to then tell if DateTime.now() is on at least a day after the last saved DateTime, i.e.

(pseudocode)
lastDailyCheck = 2020.04.10
now = 2020.04.11

=>现在是lastDailyCheck之后的一天。

=> now is a day after the lastDailyCheck.

这应该已经可以了如果它是新的一天的00:01,即使lastDailyCheck是前一天的23:58,这意味着两个DateTime之间的差可以低至分钟。

This should already work if it is 00:01 on the new day, even if the lastDailyCheck was on 23:58 the day before, meaning the difference can be as low as minutes between the 2 DateTimes.

结果证明这确实很复杂!

Turns out this is really complicated!

DateTime.Now()。isAfter(lastDailyCheck)

这仅检查现在是否在之后

DateTime.Now()。isAfter(lastDailyCheck)& & lastDailyCheck.day!= DateTime.Now()。day

我认为这很聪明。如果日期不同,并且最后一天是之后,那么它确实可以识别出是一天后的一天-但是后来我意识到,当两个月的15日都说完时,它会出错-那么 lastDailyCheck.day 等于 DateTime.Now()。day

I thought this was clever. If the day is different and it is after the last then it does work in recognizing it is a day later - but then I realized it would bug out when both days are say on the 15th of the month - then lastDailyCheck.day would equal DateTime.Now().day.

您认为这里可能发生什么?

What do you think would be possible here?

推荐答案

我不知道扑打,但我的方法会是不存储最后一张支票,而是存储应该进行下一张支票的日期。因此,当您执行检查时,您将计算下一个午夜并将其存储。现在您可以使用isAfter。

I don't know flutter, but my approach would be to not store the last check, but store the date at which the next check should occur. So when you perform a check you calculate the next midnight and store that. Now you can use isAfter.

在javascript中,它看起来像这样:

In javascript this would look something like this:

const now = new Date();

//this also handles overflow into the next month
const nextCheck = new Date(now.getYear(), now.getMonth(), now.getDate() + 1)

//store nextCheck somewhere

//in js there is no isAfter, you just use >
if(new Date() > nextCheck) {
   //do the thing
}

当然,每次您想要比较时,您也可以计算 nextCheck ,但是如果可以避免的话,我不喜欢一遍又一遍地执行相同的计算

of course you could also calculate nextCheck every time you want to compare it, but I dislike performing the same calculation over and over if I can avoid it.

这里要提到的是时区,具体取决于您的日期库,如果您的系统和用户时区对齐,则可能需要更改日期。

A thing to mention here is timezones, depending on your date library and if your system and user timezones align, you may need to shift the date.

这篇关于我如何判断DateTime.Now()是否在其他DateTime之后的一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆