如果 php 日期是存储的 mysql 日期之后 24 小时

发布于 2024-09-08 14:40:32 字数 504 浏览 3 评论 0原文

我正在尝试执行一个函数来根据数据库中的内容检查 php 日期。如果当前日期 (YYYY-MM-DD HH:MM:SS) 是存储的数据库日期之后 24 小时,那么它将继续,否则它将不会执行任何操作。如果这有意义吗?

以下是我试图让它工作的方法,但不是 100% 确定如何:

$now = date("Y-m-d H:i:s");

foreach($results as $item) {
  if (  /*item date is 24 hours or more earlier than $now*/ ) { /* this is what I'm not sure how to do */
     //do something

  } else {
    //do nothing
  };
};

如果有人可以帮助我让它工作,我将非常感激。我只是不知道如何将 $item->date 与 $now 进行比较,看看 $item->date 是否比 $now 晚 24 小时或更长时间。

I'm trying to do a function that will check the php date against what is in the database. If the current date (YYYY-MM-DD HH:MM:SS) is 24 hours after the stored database date, then it will continue, otherwise it won't do anything.. If that makes sense?

Here's how I'm trying to get it to work, but not 100% sure how:

$now = date("Y-m-d H:i:s");

foreach($results as $item) {
  if (  /*item date is 24 hours or more earlier than $now*/ ) { /* this is what I'm not sure how to do */
     //do something

  } else {
    //do nothing
  };
};

If someone could help me get this working, I'd greatly appreciate it. I just don't know how to compare $item->date with $now and see if $item->date is 24 hours or more behind $now..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瑕疵 2024-09-15 14:40:32

您可以使用 strtotime 代替日期数学。我个人认为读起来要好得多。

if (strtotime($item->date) <= strtotime('-1 day')) {
  // date is more than or equal to 24 hours old
}

You can use strtotime instead of date math. Personally I think it reads much better.

if (strtotime($item->date) <= strtotime('-1 day')) {
  // date is more than or equal to 24 hours old
}
心欲静而疯不止 2024-09-15 14:40:32
foreach($results as $item) {
  if (time() >= strtotime($item['date']) + 86400) {
    // current time is 86400 (seconds in one day) or more greater than stored time
  } else {
    //do nothing
  };
};

请注意,如果存储的日期与服务器不在同一时区,您将需要弄乱时区 - 请参阅 这里作为初学者。

请注意,我将日期和时间存储在 MySQL 中作为 Unix 时间戳以避免其中一些问题。我知道这不是好的数据库实践,但 PHP 无论如何都会将时间存储为 Unix 时间戳。

foreach($results as $item) {
  if (time() >= strtotime($item['date']) + 86400) {
    // current time is 86400 (seconds in one day) or more greater than stored time
  } else {
    //do nothing
  };
};

Note that if the stored date isn't in the same timezone as the server you'll need to mess with timezones - see here for starters.

Note that I store dates and times in MySQL as Unix timestamps to avoid some of these problems. I know it's not good database practice, but then PHP stores times as Unix timestamps anyway.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文