比较日期/时间 - PHP,XML,strtotime

时间:2011-08-25 14:55:01

标签: php xml datetime conditional strtotime

Stack Overflow社区,

我一直很感激你的智慧和帮助。这是我的情况:

以下是我的XML文件的片段(这只是其中的一小部分):

    <matchup id="1" date="09/08/11" time="7:30 PM">
        <away city="New Orleans">Saints</away>
        <home city="Green Bay">Packers</home>
        <finalscore>
            <away></away>
            <home></home>
        </finalscore>
    </matchup>

好的,所以使用SimpleXML我得到这个XML数据并将其存储到各自的PHP变量中。我唯一需要帮助的是日期/时间部分。

我想基本上将比赛的日期/时间与当前时间进行比较。如果比赛的时间已经过去(或者已经开始),我想显示不同的输出。

所以这是我的PHP,但有些东西在这里没有正常工作:

foreach($week->matchup as $matchup)
{
$game_time = $matchup['time'];
$game_date = $matchup['date'];

date_default_timezone_set('US/Eastern');
$game_date2 = strtotime($game_date);
$game_date3 = date('m/d/y', $game_date2);
$time_stamp = strtotime($game_time);
$check = date("g:i A", $time_stamp);
$date_now = date('m/d/y');
$time_now = date('g:i A');

if ($game_date3 >= $date_now && $check >= $time_now) {

?>
<tr>
<td class="two"><?php echo $game_date ?></td>
<td class="two">
<input type="radio" id="<?php echo $away_city ?> <?php echo $away_teamname ?>" class="radio" name="<?php echo $week_name ?>" value="<?php echo $away_city ?> <?php echo $away_teamname ?>"></input>
    <?php echo $away_full ?>
</td>
<td class="two">
<input type="radio" id="<?php echo $home_city ?> <?php echo $home_teamname ?>" class="radio" name="<?php echo $week_name ?>" value="<?php echo $home_city ?> <?php echo $home_teamname ?>"></input>
    <?php echo $home_full ?>
</td>
<td class="two"><?php echo $game_time ?></td>
</tr>
<?php
} else {
?>
<tr>
<td class="two"><?php echo $game_date ?></td>
<td class="two">
<span><?php echo $away_full ?></span>
</td>
<td class="two">
<span><?php echo $home_full ?></span>
</td>
<td class="two"><?php echo $game_time ?></td>
</tr>
<?php
}
    } ?>

正如您在此处所看到的,我要做的只是检查XML中的日期/时间是否超过当前时间。如果是,我想显示没有输入单选按钮的输出。如果它没有超过当前时间,我想显示输出WITH输入单选按钮。

我认为问题出在我的变量设置中,使用strtotime并获取XML日期/时间以正确解析服务器时间。

我希望有人可以帮我解决这个问题!此外,我们也赞赏任何使其更加简洁和安全的建议。

2 个答案:

答案 0 :(得分:0)

我会提醒您不要使用旧的日期函数,并建议您使用DateTime类。对于上述内容,您应该查看DateTime::createFromFormat();

所以你会有这样的事情:

$game_date2 = DateTime::createFromFormat('d/m/Y H:i:s', $game_date);
$game_date3 = new DateTime();

if($game_date2 > $game_date3) {
    echo 'game yet to be played';
}

请注意,您至少需要PHP5.2.2才能比较上面代码中的日期对象。有关详细信息,请参阅DateTime::diff() page

答案 1 :(得分:0)

您无法比较日期字符串。您需要使用strtotime 然后比较它们,将它们转换为时间戳。

像这样:

$date = '09/08/11 7:30 PM';

if (strtotime($date) < time()) {
    // $date is in the past
}

所以在你的情况下:

$game_time = $matchup['time'];
$game_date = $matchup['date'];
$date = "{$game_date} {$game_time}";

if (strtotime($date) < time()) {
    // $date is in the past
}
相关问题