PHP date function - Uses and Examples

PHP date function, References, Examples, Exceptions and uses

PHP date fuction is used to format local date/time. Core of the date function is timestamp which is "the number of seconds from January 1, 1970 at 00:00" Otherwise known as the Unix Timestamp, this measurement is a widely used standard that PHP has chosen to utilize.

php date function Syntax:

string date ( string $format[, int $timestamp ] )

The date function uses letters of the alphabet to represent various parts of a typical date and time format. e.g. :

  • d: The day of the month. The type of output you can expect is 01 through 31.
  • m: The current month, as a number. You can expect 01 through 12.
  • y: The current year in two digits ##. You can expect 00 through 99

We’ll tell you the rest of the options later, but for now let’s use those above letters to format a simple date! The letters that PHP uses to represent parts of date and time will automatically be converted by PHP.

However, other characters like a slash "/ – :" can be inserted between the letters to add additional formatting. e.g.

<?php
echo date("m/d/y");
echo date("m-d-y");
?>

Output will be
02/27/10
02-27-10

respectively.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT message if using the system settings or the

Below is an example which shows, the first argument of the date function tells PHP how you would like your date and time displayed. The second argument allows for a timestamp and is optional.

This example uses the mktime function to create a timestamp for tomorrow. To go one day in the future we simply add one to the day argument of mktime. For your future reference, we have the arguments of mktime.

Note: These arguments are all optional. If you do not supply any arguments the current time will be used to create the timestamp.

  • mktime(hour, minute, second, month, day, year, daylight savings time)

<?php
$tomorrow = mktime(0, 0, 0, date("m"), date("d")+1, date("y"));
echo "Tomorrow is ".date("m/d/y", $tomorrow);
?>

Output will be
Tomorrow is 02/28/10

PHP Date – Reference

Important Full Date and Time:

  • r: Displays the full date, time and timezone offset. It is equivalent to manually entering date("D, d M Y H:i:s O")

Time:

  • a: am or pm depending on the time
  • A: AM or PM depending on the time
  • g: Hour without leading zeroes. Values are 1 through 12.
  • G: Hour in 24-hour format without leading zeroes. Values are 0 through 23.
  • h: Hour with leading zeroes. Values 01 through 12.
  • H: Hour in 24-hour format with leading zeroes. Values 00 through 23.
  • i: Minute with leading zeroes. Values 00 through 59.
  • s: Seconds with leading zeroes. Values 00 through 59.

Day:

  • d: Day of the month with leading zeroes. Values are 01 through 31.
  • j: Day of the month without leading zeroes. Values 1 through 31
  • D: Day of the week abbreviations. Sun through Sat
  • l: Day of the week. Values Sunday through Saturday
  • w: Day of the week without leading zeroes. Values 0 through 6.
  • z: Day of the year without leading zeroes. Values 0 through 365.

Month:

  • m: Month number with leading zeroes. Values 01 through 12
  • n: Month number without leading zeroes. Values 1 through 12
  • M: Abbreviation for the month. Values Jan through Dec
  • F: Normal month representation. Values January through December.
  • t: The number of days in the month. Values 28 through 31.

Year:

  • L: 1 if it’s a leap year and 0 if it isn’t.
  • Y: A four digit year format
  • y: A two digit year format. Values 00 through 99.

Other Formatting:

  • U: The number of seconds since the Unix Epoch (January 1, 1970)
  • O: This represents the Timezone offset, which is the difference from Greenwich Meridian Time (GMT). 100 = 1 hour, -600 = -6 hours

Examples

Calculate days between two given dates. For example, if $datum1 = 20071215 and $datum2 = 20081215, the output will be 366

<?php
function calculate_day_between($datum1,$datum2)
{
if( is_numeric($datum1) && is_numeric($datum2) && strlen($datum1) == 8 && strlen($datum2) == 8 )
{
$dat = ($datum1 < $datum2)? $datum1 : $datum2;
$datv = ($datum1 < $datum2)? $datum2 : $datum1;
$i = 0;
while( $dat < $datv)
{
$i++;
switch(substr($dat,6,2))
{
case ’28’: $dat += (substr($dat,4,2) == 02 && substr($dat,0,4)%4 > 0 )? 73 : 1;
break;
case ’29’: $dat += (substr($dat,4,2) == 02 && substr($dat,0,4)%4 == 0 )? 72 : 1;
break;
case ’30’: $dat += (in_array( substr($dat,4,2), array(04,06,09,11)))? 71 : 1;
break;
case ’31’: $dat += (substr($dat,4,2) == 12 )? 8870 : 70;
break;
default: $dat++;
break;
}
}
return $i-1;
}
else
{
return false;
}
}
?>

To get number of Weeks in a particular Year

<?php

$weeks_in_year = strftime("%W",strtotime("12/31/2007"));

?>

To get the number of weeks in a particular Month

date("W") – date("W",strtotime(date("F") . " 1st " . date("Y"))) + 1;

To find the business days between two dates

<?php
//The function returns the no. of business days between two dates and it skeeps the holidays
function getWorkingDays($startDate,$endDate,$holidays){
//The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
//We add one to inlude both dates in the interval.
$days = (strtotime($endDate) – strtotime($startDate)) / 86400 + 1;

$no_full_weeks = floor($days / 7);
$no_remaining_days = fmod($days, 7);

//It will return 1 if it’s Monday,.. ,7 for Sunday
$the_first_day_of_week = date("N",strtotime($startDate));
$the_last_day_of_week = date("N",strtotime($endDate));

//The two can’t be equal because the $no_remaining_days (the interval between $the_first_day_of_week and $the_last_day_of_week) is at most 6
//In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
if ($the_first_day_of_week < $the_last_day_of_week){
if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days–;
if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days–;
}
else{
if ($the_first_day_of_week <= 6) $no_remaining_days–;
//In the case when the interval falls in two weeks, there will be a Sunday for sure
$no_remaining_days–;
}

//The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
$workingDays = $no_full_weeks * 5 + $no_remaining_days;

//We subtract the holidays
foreach($holidays as $holiday){
$time_stamp=strtotime($holiday);
//If the holiday doesn’t fall in weekend
if (strtotime($startDate) <= $time_stamp && $time_stamp <= strtotime($endDate) && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7)
$workingDays–;
}

return $workingDays;
}

//Example:

$holidays=array("2006-12-25","2006-12-26","2007-01-01");

echo getWorkingDays("2006-12-22","2007-01-06",$holidays)
// => will return 8
?>

To count quarters between dates

function countQuarters($begindate, $enddate)
{
if (!isset($begindate) || empty($begindate) || !isset($enddate) || empty($enddate))
return -1;

$countyears = date("Y", strtotime($enddate)) – date("Y", strtotime($begindate));
$quarters = 0;

if (date("Y", strtotime($enddate)) == date("Y", strtotime($begindate)))
{
if (date("m", strtotime($enddate)) != date("m", strtotime($begindate)))
{
if (date("m", strtotime($enddate)) > date("m", strtotime($begindate)))
{
$difference = date("m", strtotime($enddate)) – date("m", strtotime($begindate));

$quarters += ceil((int) $difference / 4);
}
else
{
return -1;
}
}
}
else
{
$quarters = (int) $countyears * 4;
if (date("m", strtotime($enddate)) != date("m", strtotime($begindate)))
{
if (date("m", strtotime($enddate)) > date("m", strtotime($begindate)))
{
$difference = date("m", strtotime($enddate)) – date("m", strtotime($begindate));

$quarters += ceil((int) $difference / 4);
}
else
{
$afterbegin = 12 – (int) date("m", strtotime($begindate));
$untilend = date("m", strtotime($enddate));

$quarters = ($quarters – 4) + ceil(($afterbegin + $untilend) / 4);
}
}
}

return $quarters;
}

Country Zone : Time Zone Name
-12 : Dateline Standard
-11 : Samoa Standard Time
-10 : Hawaiian Standard Time
-8 : Pacific Standard Time
-7 : Mexican Standard Time, Mountain Standard Time
-6 : Central Standard Time, Mexico Standard Time
-5 : Eastern Standard Time Eastern Time, SA Pacific Standard Time
-4 : Atlantic Standard Time, SA Western Standard Time, Pacific SA Standard Time
-3.5 : Newfoundland Standard Time
-3 : SA Eastern Standard Time, E. South America Standard Time
-2 : Mid:Atlantic Standard Time
-1 : Azores Standard Time, Cape Verde Standard Time
0 : Universal Coordinated Time, Greenwich Mean Time
1 : Romance Standard Time, Central Africa Standard Time, Central European Standard Time
2 : Egypt Standard Time, South Africa Standard Time, E. Europe Standard Time, FLE Standard Time, GTB Standard Time
3 : Arab Standard Time, E. Africa Standard Time, Arabic Standard Time, Russian Standard Time
3.5 : Iran Standard Time
4 : Arabian Standard Time, Caucasus Standard Time, Afghanistan Standard Time
5 : West Asia Standard Time
5.5 : India Standard Time
5.75 : Nepal Standard Time
6 : Central Asia Standard Time
6.5 : Myanmar Standard Time
7 : SE Asia Standard Time, North Asia Standard Time
8 : China Standard Time, W. Australia Standard Time, Singapore Standard Time, Taipei Standard Time, North Asia East Standard Time
9 : Tokyo Standard Time, Korea Standard Time, Yakutsk Standard Time
9.5 : AUS Central Standard Time, Cen. Australia Standard Time
10 : AUS Eastern Standard Time, E. Australia Standard Time
West Pacific Standard Time, Tasmania Standard Time, Vladivostok Standard Time
11 : Central Pacific Standard Time
12 : Fiji Standard Time, New Zealand Standard Time
13 : Tonga Standard Time

To generate an array of dates that are mondays or any given dates best used for reporting purposes

function getMondays($year) {
$newyear = $year;
$week = 0;
$day = 0;
$mo = 1;
$mondays = array();
$i = 1;
while ($week != 1) {
$day++;
$week = date("w", mktime(0, 0, 0, $mo,$day, $year));
}
array_push($mondays,date("r", mktime(0, 0, 0, $mo,$day, $year)));
while ($newyear == $year) {
$test = strtotime(date("r", mktime(0, 0, 0, $mo,$day, $year)) . "+" . $i . " week");
$i++;
if ($year == date("Y",$test)) {
array_push($mondays,date("r", $test));
}
$newyear = date("Y",$test);
}
return $mondays;
}

Here’s a way to return the Internet Time with correct date:

<?php
$curtime = time();
$utcdiff = date(‘Z’, $curtime); // get difference to UTC in seconds
$bmttime = $curtime – $utcdiff + 3600; // BMT = UTC+0100
$ssm = date(‘H’, $bmttime)*3600 + date(‘i’, $bmttime)*60 + date(‘s’, $bmttime); // seconds since midnight (BMT)
$ibeats = $ssm/86.4; // 86400 seconds = 1000 beats, so 1 beat = 86.4 seconds

echo ‘i.Beats : ‘ . date(‘D, d M Y’, $bmttime) . ‘ @’ . $ibeats;
?>

Note: If you would try date(‘D, d M Y @B’, $bmttime), the resulting beats would be wrong because the timezone used for calculation of the beats within the date() function is still your local one but the timestamp is UTC+0100. Another working way would be:

<?php
$curtime = time();
$utcdiff = date(‘Z’, $curtime); // get difference to UTC in seconds
$bmttime = $curtime – $utcdiff + 3600; // BMT = UTC+0100

echo ‘i.Beats : ‘ . date(‘D, d M Y’, $bmttime) . ‘ @’ . date(‘B’, $curtime);
?>

Other Handy Functions for dates in php

To check for any particular date use checkdate function

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

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

Example:

<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>

The above example will output:

bool(true)
bool(false)

date_default_timezone_set — Sets the default timezone used by all date/time functions in a script

date_default_timezone_get — Gets the default timezone used by all date/time functions in a script

date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end
Syntax: array date_sun_info ( int $time , float $latitude , float $longitude )

date_sunrise — Returns time of sunrise for a given day and location
Syntax: mixed date_sunrise ( int $timestamp [, int $format [, float $latitude [, float $longitude [, float $zenith [, float $gmt_offset ]]]]] )
date_sunrise() returns the sunrise time for a given day (specified as a timestamp ) and location.

date_sunset — Returns time of sunset for a given day and location
Syntax: mixed date_sunset ( int $timestamp [, int $format [, float $latitude [, float $longitude [, float $zenith [, float $gmt_offset ]]]]] )
date_sunset() returns the sunset time for a given day (specified as a timestamp ) and location.

gettimeofday — Get current time
Syntax: mixed gettimeofday ([ bool $return_float ] )
This is an interface to gettimeofday(2). It returns an associative array containing the data returned from the system call.

microtime — Return current Unix timestamp with microseconds
Syntax: mixed microtime ([ bool $get_as_float ] )
microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.

mktime — Get Unix timestamp for a date
Syntax: int mktime ([ int $hour [, int $minute [, int $second [, int $month [, int $day [, int $year [, int $is_dst ]]]]]]] )
Returns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.

0 I like it
0 I don't like it