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

后端 未结 5 1498
庸人自扰
庸人自扰 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 17:54

    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.

    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
    }
    

    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.

提交回复
热议问题