【问题标题】:How can i use date_diff function with string values如何将 date_diff 函数与字符串值一起使用
【发布时间】:2015-04-30 11:57:40
【问题描述】:

我有 2 个字符串值,例如“24/10/2015”和“23/10/2015”,它们是动态值。而且我需要这两个值之间的夜间计数,所以我尝试使用 date_diff 但我无法管理它。我尝试过 strtotime、date_create_from_format 等,但没有奏效。有什么建议吗?

示例代码:

$checkout = $_COOKIE['cout'];
$checkin = $_COOKIE['cin'];
$nights = date_diff(strtotime($checkout),strtotime($checkin));

【问题讨论】:

  • 那么这个问题我们在哪里呢? (仅供参考:您可以接受对您的帮助最大并解决您的问题的答案(meta.stackexchange.com/q/5234)!)

标签: php string date strtotime


【解决方案1】:

这应该适合你:

只需用DateTime::createFromFormat() 创建一个DateTime 对象,然后你就可以得到diff() 的不同之处,如下所示:

<?php

    $dateOne = "24/10/2015";
    $dateTwo = "23/10/2015";

    $dateOne = DateTime::createFromFormat("d/m/Y", $dateOne);
    $dateTwo = DateTime::createFromFormat("d/m/Y", $dateTwo);
    $interval = $dateOne->diff($dateTwo);
    echo $interval->format("%d " . ($interval->d > 1 || $interval->d == 0?"nights":"night"));

?>

输出:

1 night

Demo

【讨论】:

    【解决方案2】:

    这里是解决方案。

    $checkout = $_COOKIE['cout'];
    $checkin = $_COOKIE['cin'];
    $datediff = strtotime($checkout) - strtotime($checkin);
    $night = floor($datediff/(60*60*24));
    

    【讨论】:

      【解决方案3】:

      试试这个

       $checkout = date_create("2015-10-12");
       $checkin = date_create("2015-10-05");
       $nights = date_diff($checkout,$checkin);
      
       print_r($nights);
      

      你会得到这样的对象数组,

      DateInterval Object
      (
          [y] => 0
          [m] => 0
          [d] => 7
          [h] => 0
          [i] => 0
          [s] => 0
          [weekday] => 0
          [weekday_behavior] => 0
          [first_last_day_of] => 0
          [invert] => 1
          [days] => 7
          [special_type] => 0
          [special_amount] => 0
          [have_weekday_relative] => 0
          [have_special_relative] => 0
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-24
        • 1970-01-01
        • 2017-04-16
        • 1970-01-01
        • 1970-01-01
        • 2014-06-11
        • 1970-01-01
        相关资源
        最近更新 更多