gpt4 book ai didi

php - 时间戳(具有不同的时区格式)在未来吗?

转载 作者:可可西里 更新时间:2023-10-31 23:30:55 26 4
gpt4 key购买 nike

我得到的时间戳格式如下:

Mon Jul 28 11:39:29 GMT-05:00 2014Mon Jul 28 13:39:29 GMT+02:00 2014Thu Jul 17 00:02:02 UTC 2014Fri Jul 18 14:47:01 UTC 2014

I need to add X minutes to that and return true/false if the result is in the future. The trick is the timestamps can be in any timezone, and timezone might be expressed as UTC or GMT (see above examples).

Here is the code I wrote so far, but I do not know how to continue:

function isFuture($dateTimeStr, $minToAdd) {    
$date1 = DateTime::createFromFormat("D M d H:i:s P Y", $dateTimeStr);

// Something like $date1->date_interval_create_from_date_string('30 minutes);
$date1->add(date_interval_create_from_date_string($minToAdd . ' minutes'));

$now = new DateTime("now");
return $date1 > $now;
}

echo isFuture("Mon Jul 28 14:39:29 GMT-05:00 2014", 30) ? "Future" : "Past";
echo isFuture("Fri Jul 18 14:47:01 UTC 2014", 30) ? "Future" : "Past";

回答我自己的问题:

function isFuture($dateTimeStr, $minToAdd) {    
$t = strtotime($dateTimeStr) + ($minToAdd*60);
return $t > time();
}

最佳答案

只需使用 DateTime::getTimezone()获取 $date1 的工作时区并将其用于您的 $now DateTime 对象:

function isFuture($dateTimeStr, $minToAdd) {    
$date1 = DateTime::createFromFormat("D M d H:i:s P Y", $dateTimeStr);

// Something like $date1->date_interval_create_from_date_string('30 minutes);
$date1->add(date_interval_create_from_date_string($minToAdd . ' minutes'));

$now = new DateTime("now", new DateTimeZone($date1->getTimezone()));
return $date1 > $now;
}

这将适用于任何时区。但是,如果时区始终是 GMT/UTC,您可以将其硬编码到您的函数中:

$now = new DateTime("now", new DateTimeZone('GMT'));

关于php - 时间戳(具有不同的时区格式)在未来吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25002815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com