php递增时间戳错误?

标签 php timestamp

我有一个分页功能,可以按周翻阅时间表并提前日期,并显示与新日期相关的详细信息。

在测试一些新数据时,我遇到了分页问题。因为它不会在 2012 年 10 月 22 日通过。

调试代码我最终找到了问题的根源,即将表示 22/10/2012 的日期戳增加 7 天返回(通过 strftime)28/10/2012 的日期,而显然我正在期待一个日期2012 年 10 月 29 日。此错误有效地导致连续循环,因为 %W(驱动每周分页)对于 22/10/2012 为 43,对于 28/10/2012 为 43,当然对于 29/10/2012 应该为 44。

在隔离和重现此问题的快速测试中,我使用了以下内容:

/*
 * test %W
 */

$time_Stamp_1 = mktime(0,0,0,10,22,2012);
echo "date : " . strftime("%d/%m/%Y", $time_Stamp_1);
echo "W for first time stamp " . $time_Stamp_1 . " is " . strftime("%W", $time_Stamp_1); 

$time_Stamp_1a = $time_Stamp_1 += (60 * 60 * 24 * 7);
echo "new date : " . strftime("%d/%m/%Y", $time_Stamp_1a);
echo "W for new date time stamp: " . strftime("%W", $time_Stamp_1a);

$time_Stamp_2 = mktime(0,0,0,10,29,2012);
echo "W for second time stamp: " . strftime("%W", $time_Stamp_2);

分页在我测试过的所有其他周之间愉快地移动,并且显然适本地使用了这种增量/减量。

希望我遗漏了一些明显的东西。有什么想法吗?

最佳答案

PHP DateTime类是要走的路:-

$inFormat = 'd/m/Y h:i';
$outFormat = 'd/m/Y';
$date = DateTime::createFromFormat($inFormat, '22/10/2012 00:00');
$interval = new DateInterval('P7D');
for($i = 0; $i < 10; $i++){
    $date->add($interval);
    var_dump($date->format($outFormat) . " is in week " . $date->format('W'));week');
}

给出以下输出:-

string '29/10/2012 is in week 44' (length=24)
string '05/11/2012 is in week 45' (length=24)
string '12/11/2012 is in week 46' (length=24)
string '19/11/2012 is in week 47' (length=24)
string '26/11/2012 is in week 48' (length=24)
string '03/12/2012 is in week 49' (length=24)
string '10/12/2012 is in week 50' (length=24)
string '17/12/2012 is in week 51' (length=24)
string '24/12/2012 is in week 52' (length=24)
string '31/12/2012 is in week 01' (length=24)

快速浏览一下日历就知道这是正确的。

请参阅此处了解有效的格式字符串 http://us.php.net/manual/en/datetime.createfromformat.php
另请参阅DateInterval类。

请参阅此处了解 DateTime::format() http://us.php.net/manual/en/function.date.php 的有效输出格式

关于php递增时间戳错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12511325/

相关文章:

php - 如何监控 PHP 脚本的 CPU 使用率

php - Laravel 验证在验证之前修改请求。失败返回原件

ruby-on-rails - ActiveModel 时间戳字段 : where does the timestamp come from?

sql - scn 如何在 Oracle 中使用 sys.smon_scn_time 映射到时间戳?

ruby-on-rails - 在 Ruby 中将 UTC 时间戳转换为 ISO 8601

php - 我们可以在一个 php 文件中使用在另一个 php 文件中定义的变量吗

php - 加载动态选择 - PHP VS AJAX

php - 主要 PHP/MySQL 登录项目,带有 session 变量

html - 如何使用 Apache 记录页面请求?

mysql - 解析时间戳以获取小时数