AlfieWebDevTips Homefor new and experienced developers
[Home Home] [Web Development Web Development ] [Code Generators Code Generators ] [Resources Resources ] [Contact Us Contact ] |WebDevTips Privacy Privacy |
Print This Page

You are here : Home - Web Development - PHP - Number of days between 2 dates

Number of days between 2 dates



If you need to get the difference between 2 dates the here's how you do it. In the script below $date1 is in a format that is a typical timestamp that might be entered in a database for example.

Basically we just mess around with the time format so we get the day, month, year in numerical format. Convert the date to seconds, convert todays date to seconds and do some simple maths to calculate the difference in days.

The Code
<? 
//a date in the past 
$date1 = "21:31:11 Mar 2, 2003 PDT"; 
//get rid of the comma 
$date1 = str_replace(",","",$date1); 
//split the date at spaces 
$date1 = split(" ",$date1); 
//get the month 
$month1 = $date1[1]; 
//get the day 
$day1 = $date1[2]; 
//get the year 
$year1 = $date1[3]; 
//get the month as a number 
switch($month1){ 
        case 'Jan': 
      $month1 = 1; 
         break; 
        case 'Feb': 
      $month1 = 2; 
         break; 
        case 'Mar': 
      $month1 = 3; 
         break; 
        case 'Apr': 
      $month1 = 4; 
         break; 
        case 'May': 
      $month1 = 5; 
         break; 
        case 'Jun': 
      $month1 = 6; 
         break; 
        case 'Jul': 
      $month1 = 7; 
         break; 
        case 'Aug': 
      $month1 = 8; 
         break; 
        case 'Sep': 
      $month1 = 9; 
         break; 
        case 'Oct': 
      $month1 = 10; 
         break; 
        case 'Nov': 
      $month1 = 11; 
         break; 
        case 'Dec': 
      $month1 = 12; 
         break; 

//get todays day 
$day2 = date ("j"); 
//get todays month 
$month2 = date ("n"); 
//get todays year 
$year2    = date ("Y"); 
//use mktime to convert dates into seconds 
$date_1    = mktime(0,0,0,$month1, $day1, $year1); 
$date_2    = mktime(0,0,0,$month2, $day2, $year2); 
//subtract todays date from the old date 
$seconds = $date_2-$date_1 ; 
//if the date1 was in the future then simply do 
//$seconds = $date_1-$date_2 ; 
//divide by 86400 (number of seconds in a day) 
$daydiff = ceil($seconds/86400) ; 
//output the value 
echo "The difference between date 1 [d/m/yyyy] [$day1 / $month1 / $year1] and date 2 [d/m/yyyy] [$day2 / $month2 / $year2] is ".$daydiff. " days"; 
?> 

Script output