【问题标题】:How do i know if a time is elapsed/expired in php?我如何知道 php 中的时间是否已过/已过期?
【发布时间】:2011-03-04 11:54:39
【问题描述】:

这是场景

我想知道像 '2011-03-04' 这样的日期和像 '17:06:00' 这样的时间是否在特定的时区中,例如 'IST/PDT/CDT' 用php 过去了吗?

有什么功能可以检查这个

 $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";

【问题讨论】:

标签: php datetime timezone timestamp


【解决方案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";

?>

【讨论】:

  • @tobyS 谢谢,你能检查一下 $elapsedTime = new DateTime('2011-03-04 17:20:00', new DateTimeZone( 'IST' ));它返回“未来”而不是“过去”
  • 嗯,IST 被解释为 +0200。那是正确的偏移量吗? IST 未在php.net/manual/en/timezones.php 上列为有效时区名称。也许您可以切换到受支持的名称?
  • 您指定的时间在此处转换为“Fri, 04 Mar 2011 17:20:00 +0200”,当转换为“Fri, 04 Mar 2011 16:20:00 +0100”时我切换到“欧洲/柏林”。
  • 它在那里,被称为“亚洲/加尔各答”
【解决方案2】:

PHP 不理解那些时区:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 2015-11-27
    相关资源
    最近更新 更多