PHP DATE and TIME Functions, warnings

March 22, 2012

updated 2019-09-21

The Current Date, Time


today (yyyy-mm-dd): echo date("Y-m-d") ;
today (mm-dd-yyyy): echo date("m-d-Y") ;
this year (yyyy): echo date('Y') ;

date("F jS Y, h:i:s a T", time() )
ex: October 1st 2012, 05:05:31 pm EDT
(ex: USA Eastern time zone during DST)
j = day of the month 1-31 without leading 0.
d = day of the month 01-31 with leading 0. – always 2 digits.

date("Y-m-d, h:i:s a T", time() )
ex: 2012-10-01, 05:05:31 pm EDT
To see all the formatting options for date() and gmdate(),
go to http://us2.php.net/manual/en/function.date.php

Either single or double quotes are fine. If there are no spaces in the format (1st 3 examples), quotes may not be necessary.

Date and Time, GMT:

gmdate("F dS Y, h:i a T" ) ex: October 01st 2012, 10:05 pm GMT
gmdate("D M jS Y h:i a ", time() - 3600*5) . "EST"
ex: Mon Feb 2nd 2009 02:16 pm EST

For a “one event” example, this simple bit of code uses the gmdate() function to shift the time to another zone – adding or subtracting the # of hours different. However, if your web site server is not set to the time zone you want, of course, you should change it, not play with gmdate(). If your site is one of many on a (co-hosting, ISP) server and the server’s time zone is not the one you want, the best approach is to set the time you want in a php.ini file at the root of your site.

Converting aka re-formatting a date:

ex: from Y-m-d , stored in a database, to m-d-Y for display:

list($YY,$mm,$dd) = explode('-', $date_stored);
$newdate = $mm.'-'.$dd.'-'.$YY;
or
date("m-d-Y", strtotime($date_stored) );
can be used to convert it to the 10 digit number and then the date function converts and re-formats it.

ex: to convert from the (Unix) “number of seconds since 1-1-1970” (what php refers to with their “mktime” function) to a readable date and time:

date('Y-m-d H:i:s', $unixtime)
this is the same as mysql’s
FROM_UNIXTIME($unixtime)

 


validating date-time input

FORMAT:
checkdate ( int $month , int $day , int $year ) : bool

example:
if ( !checkdate( $mo, $da, $yr ) )
$message .= "This date, $mo-$da-$yr, is not a valid date " ;

The month is between 1 and 12 inclusive.
The day is within the allowed number of days for the given month. Leap years are taken into consideration.
The year is between 1 and 32767 inclusive.

$datex = “mm-dd-yyyy”;
SUBSTR($datex,0,2).'-'.SUBSTR($datex,3,2).'-'.SUBSTR($datex,6,4) ;
if ( !checkdate( SUBSTR($datex,0,2), SUBSTR($datex,3,2), SUBSTR($datex,6,4) ) )
$message .= 'This date, mm-dd-yyyy, is not a valid date ' ;

 


difference in times

difference in seconds:

2014-05-14 22:50:00 == $timestamp1 ex: time stamp from a database

strtotime($tmestamp1) - strtotime($tmestamp2)
both are converted to unixtime (secs. since 1-1-1970)


echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";

          time() – 3600*7 adjusts GMT to PST
1400128162 == time()
1400128162 == strtotime( "now" )
Wed 2014-05-14 09:29:22 pm = gmdate("D Y-m-d h:i:s a ", time() - 3600*7)
Wed 2014-05-14 09:29:22 pm = gmdate("D Y-m-d h:i:s a ", strtotime("now") - 3600*7)
Wed 2014-05-14 09:29:22 pm = date("D Y-m-d h:i:s a ", time() - 3600*7)
Wed 2014-05-14 09:29:22 pm = date("D Y-m-d h:i:s a ", strtotime("now") - 3600*7)
Wed 2014-05-14 21:29:22 = date("D Y-m-d H:i:s ", strtotime("now") - 3600*7)

both date() and gmdate() : Format a GMT/UTC date/time :
Greenwich Mean Time (GMT)
the operating system shifts the time to the time zone you gave it.
both date() and gmdate() set it back to GMT and so you have to adjust for it
again in the 2 functions. ( – 3600*7 sets it for PST )

 

get a persons age in years


$dob = '06-15-1988'; # (for example)
$bday = explode("-", $dob) ;
$birth = $bday[2].'-'.$bday[0].'-'.$bday[1] ; # Y-m-d
$today = date('Y-m-d', time() ) ;
$diff = strtotime($today) - strtotime($birth);
$years = floor($diff / (365.25*60*60*24));

echo $years . ' yrs old '; # example: “27 yrs old” for the first half of 2016 then 28 during the 2nd half.

 

another way to convert from a (database) string date to a date formaat

$date = '05/Feb/2010:14:00:01';
$dateInfo = date_parse_from_format('d/M/Y:H:i:s', $date);
$unixTimestamp = mktime(
$dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
$dateInfo['month'], $dateInfo['day'], $dateInfo['year'] );
echo $unixTimestamp ;

result: 1265378401


$date = '2015-08-28';
$datestamp = date_create_from_format('Y-m-d', $date) ;
echo $datestamp->format('Y-m-d') ;

result: “2015-08-28”


$date = new DateTime('2015-11-27');
print_r ( $date );

print_r result:
“DateTime Object ( [date] => 2015-11-27 00:00:00.000000 [timezone_type] => 3 [timezone] => UTC )”
One problem with DateTime is that it will convert the timezone.

 


 

statements to separate evenings and weekends


$dayofweek = gmdate( "D", time() ) ; # Mon, Tue, ...

if ($dayofweek == 'Sat' OR $dayofweek == 'Sun')
$weekend = TRUE ;
else
$weekend = FALSE ;

$theHour = gmdate( "H", time() ) ; # 1-24 (17 = 5pm)


if ($theHour >= 17 OR $weekend == TRUE)
{ # 17 = 5pm
# no one is at work; party time!
}

 


 

Function to convert seconds to days, hours, minutes, and seconds


function dayHrsMinSec ( $secs )
{
$day = 0 ;
$hrs = 0 ;
$min = 0 ;
$sec = 0 ;
$rem = (int)$secs ;
$dhms = '';
 
if ( $rem >= 86400 )
{
$day = FLOOR($rem/86400) ;
$rem = (int)fmod($rem,86400) ;
}
 
if ( $rem >= 3600 )
{
$hrs = (int)FLOOR($rem/3600) ;
$rem = (int)fmod($rem,3600) ;
}
 
if ( $rem >= 60 )
{
$min = (int)FLOOR($rem/60) ;
$rem = (int)fmod($rem,60) ;
}
 
if ( $rem > 0 )
$sec = $rem ;
 
if ( $day > 0 ) $hms = $day.' day ' ;
if ( $hrs > 0 ) $hms = $hrs.' hr ' ;
if ( $min > 0 ) $hms .= $min.' min ' ;
if ( $sec > 0 ) $hms .= $sec.' sec ' ;
 
return $dhms ;
}

 


2014-05-14 22:50:00 == $timestamp1 – ex: from a database

timestamp for $yesterday – to compare to a database
$yesterday = date("Y-m-d H:i:s", mktime(0,0,0,date("m"),date("d")-1,date("Y")) )
= 2014-05-14 00:00:00
ex: SQL query . . . WHERE orders.timestamped > $yesterday

1400107800 == strtotime( $timestamp1 )
1400107800 == strtotime('2014-05-14 22:50:00')

1400130706 == time()
1400107800 == strtotime($timestamp1)
22906 = (time() - strtotime($timestamp1) )
22906 = (strtotime("now") - strtotime($timestamp1) )
22906 secs = 6 hrs 21 min 46 sec

weekly totals by date (or subttl)

$querysubttls =
'SELECT WEEKOFYEAR(substring(date_purchased, 1, 10)) AS saleweek,
substring(date_purchased, 1, 10) AS saledate,
SUM(order_total) AS subttl
FROM orders
WHERE date_purchased > "2014-01-01 00:00:00"
GROUP BY saleweek
ORDER BY saleweek ';
$daysubttls = mysql_query($querysubttls);
while($sub = mysql_fetch_object($daysubttls))
{
echo '<br> '. sprintf("%02.0f",$sub->saleweek).
' Mon.' . $sub->saledate. ' : $' . sprintf("%08.2f",$sub->subttl) ;
}


There are places where quotes are requested but not necessary, and php gives a [pointless] warning.
Xhtml is just as bad if not worse at wanting quotes everywhere, even-though they are not necessary. The browsers don’t need them. The quotes are only for “show”, and combined with php, or any other scripting language,(example: javascript) we end up with quotes within quotes within quotes! It gets absurd. Much more, text becomes impossible to read, with all the backslashing going on. … not to mention all the problems with a program not running and no error messages because of some mis-matched quote!

use your IP address, (or 127… if on your pc) to turn on debugging just for you.

if ( getenv("REMOTE_ADDR") == '127.0.0.1' ) {
@ini_set('display_errors', '1');
error_reporting(E_ALL ^ E_NOTICE);
}

or
error_reporting(E_ERROR);
or
error_reporting(E_ALL ^ E_DEPRECATED ^ E_NOTICE );
( ALL except, not DEPRECATED and not NOTICE’s )


Changing The Time Settings for Your Linux Box

For any OS installation, you must know your Time Zone. This is expressed in terms of a city, a state or a country. You must also decide how to set BIOS time, and we may follow two strategies here:

Linux Only Machine

In this case you should set BIOS time to UTC (GMT) time. DST changes will be dynamically managed by Time Zone configurations.

MS Windows

Windows handles time in a more primitive way than Linux. For Windows, BIOS time is allways your local time, so DST changes are more aggressive because they directly change hardware clock. And since both Linux and Windows initially get and set time from the hardware, when they are together, Linux must handle it in the same way. So set BIOS time to your localtime.

Setting Time Zone

the /etc/sysconfig/clock file

On Red Hat Linux and derived systems, you can set the hardware clock strategy and Time Zone using the timeconfig command, that shows a user-friendly dialog. You can also use it non-interactively:

Example 2. Time Configuration Tool

bash# timeconfig “Brasil/East” # set HC to localtime, and TZ to “Brazil/East”
bash# timeconfig –utc “Brasil/East” # set HC to UTC, and TZ to “Brazil/East”

Anyway, it changes /etc/sysconfig/clock file that is read at boot time. You can edit it by hand, and that is how it looks:

Example 3. /etc/sysconfig/clock file

ZONE="Brazil/East"
UTC=true
ARC=false

// US TimeZones according to DateTime’s official “List of Supported Timezones”
$aTimeZones = array(
‘America/Puerto_Rico’=>’AST’,
‘America/New_York’=>’EDT’,
‘America/Chicago’=>’CDT’,
‘America/Boise’=>’MDT’,
‘America/Phoenix’=>’MST’,
‘America/Los_Angeles’=>’PDT’,
‘America/Juneau’=>’AKDT’,
‘Pacific/Honolulu’=>’HST’,
‘Pacific/Guam’=>’ChST’,
‘Pacific/Samoa’=>’SST’,
‘Pacific/Wake’=>’WAKT’,
‘Europe/Paris’=>’UTC’
);


“To date any product that has not had a onboard clock would have failed to satisfy the version 4.0 persistence requirements.
“Modern personal computer motherboards have a backup battery to run the clock circuit … while the system is turned off.

Hardware Requirements
“Time and date are supplied by an on-board clock accessible via memory mapped I/O

it is the job of the computer to maintain the date and time and it is the job of the operating system to make it available to applications. An application that changes the date and, or, time, does so through the functions provided by the operation system.


PHP’s 5.3 and beyond, overbearing strtotime warning,
demanding inappropriate redundant date assignments

How to stop php error “It is not safe to rely on the system’s timezone”

Warning: strtotime(): It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function.

 @date_default_timezone_set(@date_default_timezone_get()); 

This is a problem created by php 5.3 and beyond. There is nothing un-safe about letting operating systems do their jobs. If, at your discretion, you choose to change your web sites’ time zone to something other than that of your computer, fine (especially likely on shared hosting). There is nothing un-safe about that either. Just add the line
date.timezone = 'America/New_York' (for example) to your web site’s php.ini file.

If your web site’s time zone is correct but, as of php 5.3, you are getting this annoying (above) warning message, put

 
 @date_default_timezone_set(@date_default_timezone_get()); 

in your config file or where-ever. (your first universally included file)
It tells php explicitly, that your date and time-zone (from the computer, from the operating system?) are just fine.
Also, it will now run date and time functions much faster … a failure in php.
[see our post “php 5.3 strtotime() error”]


Using the PHP mktime Function


Yesterday in 2 formats:
yyyy mm dd = strftime("%Y %m %d", mktime(0,0,0, date("m"), date("d")-1, date("Y")))
yyyy-mm-dd = strftime("%Y-%m-%d", mktime(0,0,0, date("m"), date("d")-1, date("Y")))

yyyy-mm-dd is the first 10 characters-bytes of the SQL “timestamp”.
the full “timestamp” format is: “yyyy-mm-dd hh:mm:ss”

1249282800 = mktime(0,0,0, date("m"), date("d")-1, date("Y"))

Last Month = strftime("%A %B %d, %Y", mktime(0,0,0, date("m")-1, date("d"), date("Y")))

$yr20ago = strftime("%m/%d/%Y", mktime(0,0,0,date("m"),date("d"),date("Y")-20 ) ) ;
$yr20ago = '* (eg. '.$yr20ago.')' ;

# %A = the day of the week fully spelled out
# %B = the month fully spelled out
# %d = full 2 digit day of the month, 01 – 31
# %Y = 4 digit year

The ‘t’ below gives the number of days in a given month. Last day of the month:
strftime("%A %B %d, %Y", mktime(0,0,0, date("m"), date("t"), date("Y")))


$yesterday = mktime(0,0,0,date("m"),date("d")-1,date("Y"));
$today = mktime(0,0,0,date("m"),date("d"),date("Y"));
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
$lastmonth = mktime(0,0,0,date("m")-1,date("d"),date("Y"));
$nextmonth = mktime(0,0,0,date("m")+1,date("d"),date("Y"));
$lastyear = mktime(0,0,0,date("m"),date("d"),date("Y")-1);
$nextyear = mktime(0,0,0,date("m"),date("d"),date("Y")+1);
// The "t" below gives the number of days in a given month.
$lastday = mktime(0,0,0,date("m"),date("t"),date("Y"));
#
$yesterday = strftime("%A %B %d, %Y",$yesterday);
$today = strftime("%A %B %d, %Y",$today);
$tomorrow = strftime("%A %B %d, %Y",$tomorrow);
$lastmonth = strftime("%A %B %d, %Y",$lastmonth);
$nextmonth = strftime("%A %B %d, %Y",$nextmonth);
$lastyear = strftime("%A %B %d, %Y",$lastyear);
$nextyear = strftime("%A %B %d, %Y",$nextyear);
$lastday = strftime("%A %B %d, %Y",$lastday);

// snippet to add an hour or number of hours to a timestamp.
// from www.PHPexamples.net

2 hour offset:

$timePlusTwo = mktime(date("H") +2, date("i"), date("s"),
date("m"), date("d"), date("Y") );

to get a date from user-input without having to mess with 3 drop down lists:
aka, to edit-check a date without requiring the user to include leading zeros and to spell out full 4 digit years:

 

Holidays array

    $year = '2015'; 

      $fixed_holidays = array(
      $year.'-01-01' => 'New Year\'s Day',
      $year.'-02-02' => 'Groundhog Day',
      $year.'-02-12' => 'Lincoln\'s Birthday',
      $year.'-02-14' => 'Valentine\'s Day',
      $year.'-03-17' => 'St. Patrick\'s Day',
      $year.'-04-01' => 'April Fool\'s Day',
      $year.'-04-22' => 'Earth Day',
      $year.'-06-14' => 'Flag Day',
      $year.'-07-04' => 'Independence Day',
      $year.'-10-31' => 'Halloween',
      $year.'-11-11' => 'Veterans Day',
      $year.'-12-25' => 'Christmas Day',
      $year.'-12-31' => 'New Year\'s Eve',
      );
 
    $holidays = $fixed_holidays;
    // Martin Luther King Jr. Day (Third Monday in January)
    $holidayDay = date("Y-m-d",strtotime($year."-01 third monday"));
    $holidays[$holidayDay] = 'Martin Luther King Jr. Day';
    // Presidents' Day (Third Monday in February)
    $holidayDay = date("Y-m-d",strtotime($year."-02 third monday"));
    $holidays[$holidayDay] = 'Presidents\' Day';
    // Mother's Day (Second Sunday in May)
    $holidayDay = date("Y-m-d",strtotime($year."-05 second sunday"));
    $holidays[$holidayDay] = 'Mother\'s Day';
    // Memorial Day (Last Monday in May)
    $holidayDay = date("Y-m-d",strtotime($year."-06-01 last monday"));
    $holidays[$holidayDay] = 'Memorial Day';
    // Father's Day (Third Sunday in June)
    $holidayDay = date("Y-m-d",strtotime($year."-06 third sunday"));
    $holidays[$holidayDay] = 'Father\'s Day';
    // Labor Day (First Monday in September)
    $holidayDay = date("Y-m-d",strtotime($year."-09 first monday"));
    $holidays[$holidayDay] = 'Labor Day';
    // Columbus Day (Second Monday in October)
    $holidayDay = date("Y-m-d",strtotime($year."-10 second monday"));
    $holidays[$holidayDay] = 'Columbus Day';
    // Thanksgiving Day (Fourth Thursday in November)
    $holidayDay = date("Y-m-d",strtotime($year."-11 fourth thursday"));
    $holidays[$holidayDay] = 'Thanksgiving Day';
  
    // Easter holidays - requires PHP built-in function:  easter_date($year)
    $EasterDay = date("Y-m-d", easter_date($year) );
    $holidays[$EasterDay] = 'Easter'; 

    Easter is very weird:
    The date of Easter Day was defined by the Council of Nicaea in 325.AD as
    the Sunday after the first full moon which falls on or after the Spring Equinox.


foreach ($holidays as $date => $holiday):
echo "$holiday: $date <br> " ;
endforeach;

 


 

check for valid date function

full and flexible! check for valid date function: (1 input field is enough!)

if ( empty($adate) ) // ( date entered in common m-d-y order )
{
echo 'Please enter the requested Date' ;
}
else
{
if ( strpos($adate, "-") > 0 )
$dtarr = explode("-", $adate);
else
$dtarr = explode("/", $adate);
##
if (!checkdate($dtarr[0], $dtarr[1], $dtarr[2]) )
{
echo 'Please enter a valid date' );
}
else
{
$adate = date("Y-m-d", mktime(0,0,0, $dtarr[0], $dtarr[1], $dtarr[2]) );
# or
$adate = date("Y-m-d", strtotime($dtarr[2].'-'.$dtarr[0].'-'.$dtarr[1]) );
# either one puts it in yyyy-mm-dd format
}
}

mktime() is a long integer containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.
time() Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
example:

$nextWeek = time() + (7 * 24 * 60 * 60);
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";

strtotime() is also based on the Unix Epoch.
example: echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";

It should be noted in the example, above, that
time() + (7 * 24 * 60 * 60)
and strtotime("+1 week")
do not always generate the same timestamp.
The problem occurs when the daylight saving time changes.
Therefore it’s usually better to use strtotime.

checkdate():
bool checkdate( int $month, int $day, int $year )
ex: if (!checkdate($month, $day, $year) echo "please enter a valid date" ;

 


 

Simple Monthly Calendar


function showMonth($month, $year)
{
$date = mktime(12, 0, 0, $month, 1, $year);
$daysInMonth = date("t", $date);
// calculate the position of the first day
// (sunday = 1st column, etc)
$offset = date("w", $date);
$rows = 1;
#
echo ' <br> <table border=1 style="margin-left:20px;">';
echo '<tr><th colspan=7> <h3 style="margin-bottom:2px;"> '.
date("F Y", $date).' </h3> </th></tr>';
echo '<tr><th> S </th><th> M </th><th> T </th><th> W </th>
<th> T </th><th> F </th><th> S </th>
</tr>';
echo "<tr>";
#
for($i = 1; $i <= $offset; $i++)
echo "<td></td>";
# php simple monthly calendar
for($day = 1; $day <= $daysInMonth; $day++):
if( ($day + $offset - 1) % 7 == 0 && $day != 1):
echo "</tr><tr>";
$rows++;
endif;
echo "<td align=right>" . $day . "</td>";
endfor;
while( ($day + $offset) <= $rows * 7):
echo "<td></td>";
$day++;
endwhile;
echo "</tr>";
echo "</table>";
}

2 calls to the above function look like this — >

showMonth(8, 2015);
showMonth(9, 2015);

 


 

The elements, components, of the getdate() function:

$today = getdate();
foreach($today as $key=>$val)
{
echo "$key: $val <br>";
}
each element of the array is dumped to the screen
That code snippet will produce output much like the following:

seconds => 8
minutes => 53
hours => 10
mday => 8
wday => 1
mon => 9
year => 2003
yday => 250
weekday => Monday
month => September
0 => 1063032788


The elements, components, of localtime(time() ):
$today = localtime(time(),1);
“,1” above indicates we want the associative array structure:

foreach($today as $key=>$val) {
echo "$key => $val <br>";
}
each element of the array is dumped to the screen
it will produce the following results,
based on the timestamp value:
example:

tm_sec => 30
tm_min => 59
tm_hour => 10
tm_mday => 8
tm_mon => 8
tm_year => 103
tm_wday => 1
tm_yday => 250
tm_isdst => 1
Note that you should take care in using this function when using the results in mktime(). The localtime() function returns months as 0 to 11, but mktime uses months as 1 to 12. Ensure you compensate for this if you plan on using these functions together.


Leave a Reply

We try to post all comments within 1 business day