如何将date_diff函数与字符串值一起使用

时间:2015-04-30 11:57:40

标签: php string date strtotime

我有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));

5 个答案:

答案 0 :(得分:2)

这应该适合你:

只需使用DateTime创建一个DateTime::createFromFormat()对象,然后就可以获得与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

答案 1 :(得分:1)

这是解决方案。

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

答案 2 :(得分:0)

它可以在php中使用:

Windows 7

如果您没有使用正确格式的日期,请使用phps date()函数

答案 3 :(得分:0)

Try this one to solve your problem

/****Code Start*****/
<?php
$checkout = $_COOKIE['cout'];
$checkin = $_COOKIE['cin'];
$diff = abs(strtotime($checkout) - strtotime($checkin));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
printf("%d years, %d months, %d days\n", $years, $months, $days);
?>

/****Code End*****/

答案 4 :(得分:0)

试试这个

 $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
)