开发者

Calculate number of days between two given dates

开发者 https://www.devze.com 2023-03-11 02:10 出处:网络
Can anyone correct the error in my script to calculate the number of days between 2 dates. The dates have been input through a form, the variable info is as followed:

Can anyone correct the error in my script to calculate the number of days between 2 dates. The dates have been input through a form, the variable info is as followed:

[departon] => Array ( [0] => 1 [1] => June [2] => 2011 )     
[returnon] => Array ( [0] =&g开发者_JS百科t; 31 [1] => June [2] => 2011 ) 

I have written the code to calculate these dates, but its not calculating the day, it just outputs 0.

<?php
$first_date = mktime(12, 0, 0, $_POST['departon'][1], $_POST['departon'][0], $_POST['departon'][2]); 
$second_date = mktime(12, 0, 0, $_POST['returnon'][1], $_POST['returnon'][0], $_POST['returnon'][2]);
$days = $second_date-$first_date;
echo floor($days/60/60/24) . " days"; 
?>

Help would be much appreciated.


The easiest way is by using datetimes.

Consider this:

var_dump(new DateTime('1 July 2007'));

$a = new DateTime('1 July 2007');
$b = new DateTime('1 June 2001');

var_dump($a->diff($b));

The var_dump will allow you to see the different kind of time you can extract from it.

object(DateInterval)[3]
  public 'y' => int 6
  public 'm' => int 1
  public 'd' => int 0
  public 'h' => int 0
  public 'i' => int 0
  public 's' => int 0
  public 'invert' => int 1
  public 'days' => int 2221

You can convert your array to a date time very easily by using

$date = new DateTime(join(" ",$array));
$date2 = new DateTime(join(" ",$array2));
$diff = $date->diff($date2);


Here's an easy way:

$depart = strtotime(implode(' ', $_POST['departon']));
$return = strtotime(implode(' ', $_POST['returnon']));

$diff = floor(($return - $depart) / (60 * 60 * 24));

Note: there's only 30 days in June.


The mktime documentation specifies a number for the month, so you'd need to convert 'June' to '6'.

0

精彩评论

暂无评论...
验证码 换一张
取 消