PHP 7.1.24 Released

Date/Time Functions

Table of Contents

add a note add a note

User Contributed Notes 25 notes

up
7
koch.ro
11 years ago
Not really elegant, but tells you, if your installed timezonedb is the most recent:

<?php
class TestDateTimeTimezonedbVersion extends PHPUnit_Framework_TestCase
{
    public function
testTimezonedbIsMostRecent()
    {
       
ini_set( 'date.timezone', 'Europe/Berlin' );
       
ob_start();                                                                                                       
       
phpinfo(INFO_MODULES);
       
$info = ob_get_contents();                                                                                        
       
ob_end_clean();
       
$start = strpos( $info, 'Timezone Database Version' ) + 29;

       
$this->assertTrue( FALSE !== $start, 'Seems there is no timezone DB installed' );

       
$end   = strpos( $info, "\n", $start );
       
$installedVersion = substr( $info, $start, $end - $start );

       
exec( 'pecl remote-info timezonedb', &$output );
       
$availableVersion = substr( $output[2], 12 );

       
$this->assertEquals( $availableVersion, $installedVersion,
       
'The installed timezonedb is not actual. Installed: '.$installedVersion
       
.' available: '.$availableVersion
       
);
    }
}
?>
up
2
nightowl at NOS-PA-M dot uk2 dot net
16 years ago
I wanted to find all records in my database which match the current week (for a call-back function). I made up this function to find the start and end of the current week :

<?php
function week($curtime) {
   
   
$date_array = getdate (time());
   
$numdays = $date_array["wday"];
   
   
$startdate = date("Y-m-d", time() - ($numdays * 24*60*60));
   
$enddate = date("Y-m-d", time() + ((7 - $numdays) * 24*60*60));

   
$week['start'] = $startdate;
   
$week['end'] = $enddate;
   
    return
$week;
   
}
?>
up
2
mincklerstraat at softhome dot net
14 years ago
Before you get too advanced using date functions, be sure also to see the calendar functions at http://www.php.net/manual/en/ref.calendar.php .
up
2
bgold at matrix-consultants dot com
11 years ago
When debugging code that stores date/time values in a database, you may find yourself wanting to know the date/time that corresponds to a given unix timestamp, or the timestamp for a given date & time.

The following script will do the conversion either way.  If you give it a numeric timestamp, it will display the corresponding date and time.  If you give it a date and time (in almost any standard format), it will display the timestamp.

All conversions are done for your locale/time zone.

<?php
       
while (true)
        {
               
// Read a line from standard in.
               
echo "enter time to convert: ";
               
$inline = fgets(STDIN);
               
$inline = trim($inline);
                if (
$inline == "" || $inline == ".")
                        break;

               
// See if the line is a date.
               
$pos = strpos($inline, "/");
                if (
$pos === false) {
                       
// not a date, should be an integer.
                       
$date = date("m/d/Y G:i:s", $inline);
                        echo
"int2date: $inline -> $date\n";
                } else {
                       
$itime = strtotime($inline);
                        echo
"date2int: $inline -> $itime\n";
                }
        }
?>
up
1
daniel at globalnetstudios dot com
13 years ago
This dateDiff() function can take in just about any timestamp, including UNIX timestamps and anything that is accepted by strtotime(). It returns an array with the ability to split the result a couple different ways. I built this function to suffice any datediff needs I had. Hope it helps others too.

<?php
 
/********* dateDiff() function **********
   * returns Array of Int values for difference between two dates
   * $date1 > $date2 --> positive integers are returned
   * $date1 < $date2 --> negative integers are returned
   *
   * $split recognizes the following:
   *   'yw' = splits up years, weeks and days (default)
   *   'y'  = splits up years and days
   *   'w'  = splits up weeks and days
   *   'd'  = total days
   *
   * examples:
   *   $dif1 = dateDiff() or dateDiff('yw')
   *   $dif2 = dateDiff('y')
   *   $dif3 = dateDiff('w')
   *   $dif4 = dateDiff('d')
   *
   * assuming dateDiff returned 853 days, the above
   * examples would have a print_r output of:
   *   $dif1 == Array( [y] => 2 [w] => 17 [d] => 4 )
   *   $dif2 == Array( [y] => 2 [d] => 123 )
   *   $dif3 == Array( [w] => 121 [d] => 6 )
   *   $dif4 == Array( [d] => 847 )
   *
   * note: [h] (hours), [m] (minutes), [s] (seconds) are always returned as elements of the Array
   */
 
function dateDiff($dt1, $dt2, $split='yw') {
   
$date1 = (strtotime($dt1) != -1) ? strtotime($dt1) : $dt1;
   
$date2 = (strtotime($dt2) != -1) ? strtotime($dt2) : $dt2;
   
$dtDiff = $date1 - $date2;
   
$totalDays = intval($dtDiff/(24*60*60));
   
$totalSecs = $dtDiff-($totalDays*24*60*60);
   
$dif['h'] = $h = intval($totalSecs/(60*60));
   
$dif['m'] = $m = intval(($totalSecs-($h*60*60))/60);
   
$dif['s'] = $totalSecs-($h*60*60)-($m*60);
   
// set up array as necessary
   
switch($split) {
    case
'yw': # split years-weeks-days
     
$dif['y'] = $y = intval($totalDays/365);
     
$dif['w'] = $w = intval(($totalDays-($y*365))/7);
     
$dif['d'] = $totalDays-($y*365)-($w*7);
      break;
    case
'y': # split years-days
     
$dif['y'] = $y = intval($totalDays/365);
     
$dif['d'] = $totalDays-($y*365);
      break;
    case
'w': # split weeks-days
     
$dif['w'] = $w = intval($totalDays/7);
     
$dif['d'] = $totalDays-($w*7);
      break;
    case
'd': # don't split -- total days
     
$dif['d'] = $totalDays;
      break;
    default:
      die(
"Error in dateDiff(). Unrecognized \$split parameter. Valid values are 'yw', 'y', 'w', 'd'. Default is 'yw'.");
    }
    return
$dif;
  }
?>
up
1
venoel at rin dot ru
11 years ago
May be useful for somebody. This function takes on daylight saving time

<?php
Function DateDiff($date1,$date2) {
 
$timedifference=$date2-$date1;
 
$corr=date("I",$date2)-date("I",$date1);
 
$timedifference+=$corr;
  return
$timedifference;
}
?>

Example:

<?php
$d1
=mktime(2,0,0,10,28,2007);
$d2=mktime(4,0,0,10,28,2007);
$period=DateDiff($d1,$d2);
printf("<br>%s",date("I d.m.Y H:i",$d1));
printf("<br>%u hour",$period/3600);
printf("<br>%s",date("I d.m.Y H:i",$d2));
?>

Getting 2 hour instead 3.
up
0
andreencinas at yahoo dot com dot br
13 years ago
<?php
      
//function like dateDiff Microsoft
       //not error in year Bissesto

      
function dateDiff($interval,$dateTimeBegin,$dateTimeEnd) {
        
//Parse about any English textual datetime
         //$dateTimeBegin, $dateTimeEnd

        
$dateTimeBegin=strtotime($dateTimeBegin);
         if(
$dateTimeBegin === -1) {
           return(
"..begin date Invalid");
         }

        
$dateTimeEnd=strtotime($dateTimeEnd);
         if(
$dateTimeEnd === -1) {
           return(
"..end date Invalid");
         }

        
$dif=$dateTimeEnd - $dateTimeBegin;

         switch(
$interval) {
           case
"s"://seconds
              
return($dif);

           case
"n"://minutes
              
return(floor($dif/60)); //60s=1m

          
case "h"://hours
              
return(floor($dif/3600)); //3600s=1h

          
case "d"://days
              
return(floor($dif/86400)); //86400s=1d

          
case "ww"://Week
              
return(floor($dif/604800)); //604800s=1week=1semana

          
case "m": //similar result "m" dateDiff Microsoft
              
$monthBegin=(date("Y",$dateTimeBegin)*12)+
                
date("n",$dateTimeBegin);
              
$monthEnd=(date("Y",$dateTimeEnd)*12)+
                
date("n",$dateTimeEnd);
              
$monthDiff=$monthEnd-$monthBegin;
               return(
$monthDiff);

           case
"yyyy": //similar result "yyyy" dateDiff Microsoft
              
return(date("Y",$dateTimeEnd) - date("Y",$dateTimeBegin));

           default:
               return(
floor($dif/86400)); //86400s=1d
        
}

       }
?>
up
0
mail at completeideas dot com
13 years ago
For those who are using pre MYSQL 4.1.1, you can use:

TO_DAYS([Date Value 1])-TO_DAYS([Date Value 2])

For the same result as:

DATEDIFF([Date Value 1],[Date Value 2])
up
0
nickaubert at america's biggest isp dot com
14 years ago
I ran into an issue using a function that loops through an array of dates where the keys to the array are the Unix timestamp for midnight for each date.  The loop starts at the first timestamp, then incremented by adding 86400 seconds (ie. 60 x 60 x 24).  However, Daylight Saving Time threw off the accuracy of this loop, since certain days have a duration other than 86400 seconds.  I worked around it by adding a couple of lines to force the timestamp to midnight at each interval.

<?php
  $ONE_DAY
= 90000;   // can't use 86400 because some days have one hour more or less
 
for ( $each_timestamp = $start_time ; $each_timestamp <= $end_time ; $each_timestamp +=  $ONE_DAY) {

   
/*  force midnight to compensate for daylight saving time  */
   
$this_timestamp_array = getdate( $each_timestamp );
   
$each_timestamp = mktime ( 0 , 0 , 0 , $this_timestamp_array[mon] , $this_timestamp_array[mday] , $this_timestamp_array[year] );

    
// do some stuff...
 
}
?>
up
0
garyc at earthling dot net
15 years ago
I needed to calculate the week number from a given date and vice versa, where the week starts with a Monday and the first week of a year may begin the year before, if the year begins in the middle of the week (Tue-Sun). This is the way weekly magazines calculate their issue numbers.

Here are two functions that do exactly that:

Hope somebody finds this useful.

Gary

<?php
/*  w e e k n u m b e r  -------------------------------------- //
weeknumber returns a week number from a given date (>1970, <2030)
Wed, 2003-01-01 is in week 1
Mon, 2003-01-06 is in week 2
Wed, 2003-12-31 is in week 53, next years first week
Be careful, there are years with 53 weeks.
// ------------------------------------------------------------ */

function weeknumber ($y, $m, $d) {
   
$wn = strftime("%W",mktime(0,0,0,$m,$d,$y));
   
$wn += 0; # wn might be a string value
   
$firstdayofyear = getdate(mktime(0,0,0,1,1,$y));
    if (
$firstdayofyear["wday"] != 1)    # if 1/1 is not a Monday, add 1
       
$wn += 1;
    return (
$wn);
}   
# function weeknumber

/*  d a t e f r o m w e e k  ---------------------------------- //
From a weeknumber, calculates the corresponding date
Input: Year, weeknumber and day offset
Output: Exact date in an associative (named) array
2003, 12, 0: 2003-03-17 (a Monday)
1995,  53, 2: 1995-12-xx
...
// ------------------------------------------------------------ */

function datefromweek ($y, $w, $o) {

   
$days = ($w - 1) * 7 + $o;

   
$firstdayofyear = getdate(mktime(0,0,0,1,1,$y));
    if (
$firstdayofyear["wday"] == 0) $firstdayofyear["wday"] += 7;
# in getdate, Sunday is 0 instead of 7
   
$firstmonday = getdate(mktime(0,0,0,1,1-$firstdayofyear["wday"]+1,$y));
   
$calcdate = getdate(mktime(0,0,0,$firstmonday["mon"], $firstmonday["mday"]+$days,$firstmonday["year"]));

   
$date["year"] = $calcdate["year"];
   
$date["month"] = $calcdate["mon"];
   
$date["day"] = $calcdate["mday"];

    return (
$date);

}   
# function datefromweek
?>
up
0
brighn (a) yahoo (.) com
15 years ago
I needed a function that determined the last Sunday of the month. Since it's made for the website's "next meeting" announcement, it goes based on the system clock; also, if today is between Sunday and the end of the month, it figures out the last Sunday of *next* month. lastsunday() takes no arguments and returns the date as a string in the form "January 26, 2003". I could probably have streamlined this quite a bit, but at least it's transparent code. =)

<?php
 
/* The two functions calculate when the next meeting will
     be, based on the assumption that the meeting will be on
     the last Sunday of the month. */ 

 
function getlast($mon, $year) {
   
$daysinmonth = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
   
$days = $daysinmonth[$mon-1];
    if (
$mon == 2 && ($year % 4) == 0 && (($year % 100) != 0 ||
    (
$year % 400) == 0)) $days++;
    if (
$mon == 2 && ($year % 4) == 0 && ($year % 1000) != 0) $days++;
   
$lastday = getdate(mktime(0,0,0,$mon,$days,$year));
   
$wday = $lastday['wday'];
    return
getdate(mktime(0,0,0,$mon,$days-$wday,$year));
  }

  function
lastsunday() {
   
$today = getdate();
   
$mon = $today['mon'];
   
$year = $today['year'];
   
$mday = $today['mday'];
   
$lastsun = getlast($mon, $year);
   
$sunday = $lastsun['mday'];
    if (
$sunday < $mday) {
     
$mon++;
      if (
$mon = 13) {
       
$mon = 1;
       
$year++;
      }
     
$lastsun = getlast($mon, $year);
     
$sunday = $lastsun['mday'];
    }
   
$nextmeeting = getdate(mktime(0,0,0,$mon,$sunday,$year));
   
$month = $nextmeeting['month'];
   
$mday = $nextmeeting['mday'];
   
$year = $nextmeeting['year'];
    return
"$month $mday, $year";
  }
?>
up
-1
Hans
7 years ago
I needed a way to display an announcement on a shopping site, that would warn users that orders placed between a certain date range, would not be shipped until after a certain date.

I created this simple date detection code to display the notice on certain pages. You can just copy the code and save it to a file on the site and include it anywhere you need to perform a function, or display a notice.

<?php
/*
    Code to show a message only for a certain time frame.
    This is a simple include file that can be used to display a message
    on any pages that use it.
    Simply us a standard include instruction to this file on the page/s where
    you want the notice to appear.
    Written by Hans Kiesouw - hans at wotworx dot com
*/

$start = new DateTime('30-07-2011'); // DD-MM-YYYY
$endDate= new DateTime('07-08-2011'); // DD-MM-YYYY
$curdate = new DateTime(date('d-m-Y'));

if (
$start <= $curdate && $curdate <= $endDate) {
   
/*
    The message below will appear if the current date is between the start and
    endDate - used standards HTML to ensure that any code will not be
    escaped by PHP. You can use any code here to wish to execute for the
    date range.
    */
   
?>
   
    <p><strong><font color="#FF0000">Please Note: Any orders placed between July 30th and August 7th will only be shipped on August 8th. We apologize for any inconvenience and thank you for your order.</font></strong></p>
<?php 
// don't forget this last bit, it ends the if statement!
}

?>
up
-2
glashio at xs4all dot nl
13 years ago
Calculate Sum BusinessDays (Mon till Fri) between two date's :

<?php
function businessdays($begin, $end) {
   
$rbegin = is_string($begin) ? strtotime(strval($begin)) : $begin;
   
$rend = is_string($end) ? strtotime(strval($end)) : $end;
    if (
$rbegin < 0 || $rend < 0)
        return
0;

   
$begin = workday($rbegin, TRUE);
   
$end = workday($rend, FALSE);

    if (
$end < $begin) {
       
$end = $begin;
       
$begin = $end;
    }

   
$difftime = $end - $begin;
   
$diffdays = floor($difftime / (24 * 60 * 60)) + 1;

    if (
$diffdays < 7) {
       
$abegin = getdate($rbegin);
       
$aend = getdate($rend);
        if (
$diffdays == 1 && ($astart['wday'] == 0 || $astart['wday'] == 6) && ($aend['wday'] == 0 || $aend['wday'] == 6))
            return
0;
       
$abegin = getdate($begin);
       
$aend = getdate($end);
       
$weekends = ($aend['wday'] < $abegin['wday']) ? 1 : 0;
    } else
       
$weekends = floor($diffdays / 7);
    return
$diffdays - ($weekends * 2);
}

function
workday($date, $begindate = TRUE) {
   
$adate = getdate($date);
   
$day = 24 * 60 * 60;
    if (
$adate['wday'] == 0) // Sunday
       
$date += $begindate ? $day : -($day * 2);
    elseif (
$adate['wday'] == 6) // Saterday
       
$date += $begindate ? $day * 2 : -$day;
    return
$date;
}
?>
up
-2
php-contrib at i-ps dot nospam dot net
16 years ago
Someone may find this info of some use:

Rules for calculating a leap year:

1) If the year divides by 4, it is a leap year (1988, 1992, 1996 are leap years)
2) Unless it divides by 100, in which case it isn't (1900 divides by 4, but was not a leap year)
3) Unless it divides by 400, in which case it is actually a leap year afterall (So 2000 was a leap year).

In practical terms, to work out the number of days in X years, multiply X by 365.2425, rounding DOWN to the last whole number, should give you the number of days.

The result will never be more than one whole day inaccurate, as opposed to multiplying by 365, which, over more years, will create a larger and larger deficit.
up
-2
th at definitynet dot com
17 years ago
I had some problems with dates between mySQL and PHP.  PHP had all these great date functions but I wanted to store a usable value in my database tables. In this case I was using TIMESTAMP(14)  <or 'YYYYMMDDHHMMSS'>.
This is perhaps the easiest way I have found to pull the PHP usable UNIX Datestamp from my mySQL datestamp stored in the tables:

Use the mySQL UNIX_TIMESTAMP() function in your SQL definition string. i.e.

$sql= "SELECT field1, field2, UNIX_TIMESTAMP(field3) as your_date
          FROM your_table
          WHERE field1 = '$value'";

The query will return a temp table with coulms "field1" "Field2" "your_date"

The "your_date" will be formatted in a UNIX TIMESTAMP!  Now you can use the PHP date() function to spew out nice date formats.

Sample using above $sql:
200101110027