我怎么知道php中是否已经过了一段时间/过期了?

时间:2011-03-04 11:54:40

标签: php datetime timezone timestamp

这是方案

我想知道'2011-03-04'之类的日期,以及 '17:06:00'之类的时间在特定时区如'IST / PDT / CDT'是否已经过了?

是否有任何可用的功能来检查

 $strDate = '2011-03-04 17:06:00';
 $TZ      = 'IST';

 $strDate = '2011-02-01 11:16:30';
 $TZ      = 'CDT';

 $strDate = '2010-08-04 07:20:00';
 $TZ      = 'IST';

 $strDate = '2011-02-27 09:55:00';
 $TZ      = 'PST';

我在网上尝试/搜索但没有快乐,请帮助

是的,我尝试使用 DateTime ,但它对我不起作用..我的服务器在 IST TimeZone

$date = new DateTime('2011-03-04 17:06:00');
$date->setTimeZone(new DateTimeZone("PST"));
$newtime = $date->getTimestamp();
$time     = time();
if ($time > $usertime) 
    echo 'time passed';
else
    echo 'time NOT passed';

感谢tobyS,但它太过于虚伪

$elapsedTime = new DateTime(
    '2011-03-04 17:00:00', // I set it to 5PM. Now the time is 5:45 PM here in INDIA
    new DateTimeZone( 'IST' )
);

$elapsedInt = $elapsedTime->diff( new DateTime() );
echo ( $elapsedInt->invert ? 'Future' : 'Past' ) . "\n";

2 个答案:

答案 0 :(得分:1)

您可以根据时间数据创建DateTime对象,并将diff()方法用于当前时间。

示例代码:

<?php

$elapsedTime = new DateTime(
    '2010-08-04 07:20:00',
    new DateTimeZone( 'IST' )
);

$notElapsedTime = new DateTime(
    '2012-08-04 07:20:00',
    new DateTimeZone( 'IST' )
);

$elapsedInt = $elapsedTime->diff( new DateTime() );

echo ( $elapsedInt->invert ? 'Future' : 'Past' ) . "\n";

$notElapsedInt = $notElapsedTime->diff( new DateTime() );

echo ( $notElapsedInt->invert ? 'Future' : 'Past' ) . "\n";

?>

答案 1 :(得分:1)

PHP无法理解这些时区:

$timezone = 'America/New_York';
$date = new DateTime($strDate, new DateTimeZone($timezone));