【问题标题】:PHP strtotime returns whole year instead of a single dayPHP strtotime 返回全年而不是一天
【发布时间】:2014-11-05 04:26:52
【问题描述】:

我目前正在使用 PHP ROUNDABSSTRTOTIME 来计算两个日期之间的差异。

在您从新的一年中选择 $_SESSION['b_checkout'] 之前,该计算一直有效。即,如果 b_checkin 是 12 月 30 日,b_checkout 是 12 月 31 日,则返回正确的 $no_nights 为 1 天。

$_SESSION['b_checkin']$_SESSION['b_checkout'] 使用 'D F jS Y' 日期格式。例如

$_SESSION['b_checkin'] = "Wednesday, 31 December, 2014"
$_SESSION['b_checkout'] = "Thursday, 1 January, 2015"

$no_nights = round(abs(strtotime($_SESSION['b_checkout']) - strtotime($_SESSION['b_checkin']))/(60*60*24));

目前这个输出 (echo $no_nights) 363 天而不是 1 天。有什么问题?

【问题讨论】:

  • 您的日期不是strtotime 的有效格式 -> int strtotime ( string $time) time A date/time string. Valid formats are explained in [Date and Time Formats](http://php.net/manual/en/datetime.formats.date.php)

标签: php strtotime


【解决方案1】:

删除所有逗号,看看它是否有效!

$b_checkin = "Wednesday 31 December 2014";
$b_checkout = "Thursday 1 January 2015";

$no_nights = round(abs(strtotime($b_checkout) - strtotime($b_checkin))/(60*60*24));
echo $no_nights;

当 php 无法正确解释年份时,它使用当前年份进行解析。这就是你得到 363 天的结果。

【讨论】:

  • 使用 str_replace 如下并且有效: $_SESSION['b_checkin'] = str_replace(',', '', $_SESSION['b_checkin']); $_SESSION['b_checkout'] = str_replace(',', '', $_SESSION['b_checkout']);
【解决方案2】:

使用以下格式进行签到和结帐

// 'F jS Y'
$_SESSION['b_checkin'] = "31 December, 2014";
$_SESSION['b_checkout'] = "1 January, 2015";

希望这会有所帮助;)

干杯!!!

【讨论】:

    猜你喜欢
    • 2017-08-03
    • 1970-01-01
    • 2023-03-07
    • 2012-04-20
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多