繁体   English   中英

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

[英]How can i use date_diff function with string values

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

这应该为您工作:

只需使用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

演示版

这是解决方案。

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

可以在php中这样使用:

$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
echo date_diff($date1,$date2);

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

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*****/

尝试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM