简体   繁体   English

查找PHP中2个日期之间的天数

[英]Find amount of days between 2 dates in php

I have 2 dates and want to know how many the amount of days that come between them. 我有2个约会,想知道他们之间有多少天。

Lets say these two are the dates 可以说这两个是日期

2015-11-16 10:01:13 2015-11-16 10:01:13
2015-05-06 09:47:16 2015-05-06 09:47:16

The first one being right now, how can I calculate how many days are in between the two given dates? 现在是第一个,如何计算两个给定日期之间的天数?

Following my comment, I thought I would post some examples from the PHP.net manual : 在发表评论之后,我想我应该从PHP.net 手册中发布一些示例:

OOP style: OOP风格:

<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

Procedural style: 程序风格:

<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>

Both examples will output: 这两个示例将输出:

+2 days +2天

You can also compare word strings as such (when using OOP style, this is an example from PHP.net): 您还可以这样比较单词字符串(使用OOP样式时,这是PHP.net的示例):

<?php
$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");
var_dump($date1 == $date2);
var_dump($date1 < $date2);
var_dump($date1 > $date2);
?>

Producing: 生产:

bool(false) 布尔(假)
bool(true) 布尔(真)
bool(false) 布尔(假)

Using your dates: 使用日期:

OOP OOP

<?php
$datetime1 = new DateTime('2015-11-16 10:01:13');
$datetime2 = new DateTime('2015-05-06 09:47:16');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

Procedural 程序

<?php
$datetime1 = date_create('2015-11-16 10:01:13');
$datetime2 = date_create('2015-05-06 09:47:16');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>

Result from both: 两者的结果:

-194 days -194天

I sincerely hope this helps :) 我衷心希望这会有所帮助:)

Try this. 尝试这个。 It is very simple. 这很简单。

    <?php

     $date1 = strtotime("2015-11-16 10:01:13");
     $date2 = strtotime("2015-05-06 09:47:16");
     $datediff = $date1 - $date2;
     echo floor($datediff/(60*60*24))." days"; //output 194 days

    ?>

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

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