|
|
 |
mktime (PHP 3, PHP 4, PHP 5) mktime -- Get Unix timestamp for a date Descriptionint mktime ( [int hour [, int minute [, int second [, int month [, int day [, int year [, int is_dst]]]]]]] )
Warning: Note the strange order of
arguments, which differs from the order of arguments in a regular
Unix mktime() call and which does not lend itself well to leaving
out parameters from right to left (see below). It is a common
error to mix these values up in a script.
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.
Arguments may be left out in order from right to left; any
arguments thus omitted will be set to the current value according
to the local date and time.
is_dst can be set to 1 if the time is
during daylight savings time (DST), 0 if it is not, or -1 (the default)
if it is unknown whether the time is within daylight savings time
or not. If it's unknown, PHP tries to figure it out itself. This can
cause unexpected (but not incorrect) results.
Some times are invalid if DST is enabled on the system PHP is running on
or is_dst is set to 1. If DST is enabled in e.g.
2:00, all times between 2:00 and 3:00 are invalid and
mktime() returns an undefined (usually negative) value.
Some systems (e.g. Solaris 8) enable DST at midnight so time 0:30
of the day when DST is enabled is evaluated as 23:30 of the previous day.
Note:
is_dst was added in 3.0.10.
mktime() is useful for doing date arithmetic
and validation, as it will automatically calculate the correct
value for out-of-range input. For example, each of the following
lines produces the string "Jan-01-1998".
Example 1. mktime() example |
<?php
echo date("M-d-Y", mktime(0, 0, 0, 12, 32, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 13, 1, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 1998));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 98));
?>
|
|
Year may be a two or four digit value,
with values between 0-69 mapping to 2000-2069 and 70-99 to
1970-1999 (on systems where time_t is a 32bit signed integer, as
most common today, the valid range for
year is somewhere between 1901 and 2038).
Windows:
Negative timestamps are not supported under any known version
of Windows. Therefore the range of valid years includes only 1970
through 2038.
The last day of any given month can be expressed as the "0" day
of the next month, not the -1 day. Both of the following examples
will produce the string "The last day in Feb 2000 is: 29".
Example 2. Last day of next month |
<?php
$lastday = mktime(0, 0, 0, 3, 0, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
$lastday = mktime(0, 0, 0, 4, -31, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
?>
|
|
Date with year, month and day equal to zero is considered illegal
(otherwise it what be regarded as 30.11.1999, which would be strange
behavior).
See also gmmktime(),
date() and time().
User Contributed Notes
mktime
Buu-Lâm Lê
17-May-2005 04:29
little mistake in getDateDifference()
for $date1, $date2,
$date1 = mktime($dateFromTimeElements[0], $dateFromTimeElements[1], $dateFromTimeElements[2], $dateFromDateElements[1], $dateFromDateElements[0], $dateFromDateElements[2]);
->
replace mktime (0, 1, 2, 1, 0, 2)
mktime (0, 1, 2, 1, 2, 0) hour - min - sec - mon - day - year
for each parameter, i've added an intval, but perhaps
it doesn't worth it.
jemore at m6net dot fr
06-May-2005 12:39
A date enumerator function. With this, you set a begin date and an end date (timestamp format), and it will call a user function stepping one day or one month.
<?php
define ('DATE_ENUM_DAY', 1);
define ('DATE_ENUM_MONTH', 2);
function date_enumeration($dateBeginTS, $dateEndTS, $callbackfunc, $step, $param = NULL)
{
$cur = $dateBeginTS;
while($cur <= $dateEndTS)
{
$callbackfunc($cur, &$param);
if ($step == DATE_ENUM_DAY)
{
$cur = mktime(
date('h', $cur),
date('i', $cur),
date('s', $cur),
date('m', $cur),
date('d', $cur) + 1,
date('Y', $cur));
}
else if ($step == DATE_ENUM_MONTH)
{
$cur = mktime(
date('h', $cur),
date('i', $cur),
date('s', $cur),
date('m', $cur) + 1,
date('d', $cur),
date('Y', $cur));
}
else
{
die ('No step specified');
}
}
}
function cb_test($timestamp, $param)
{
echo date('r', $timestamp), ' ', $param, "<br>\n";
}
date_enumeration(
mktime(0,0,0,1,1,2000),
mktime(0,0,0,1,1,2002),
'cb_test',
DATE_ENUM_DAY
);
?>
Greg Robbins
05-May-2005 11:42
Here's an update (no pun intended) to my "generic times" function below for comverting between timestamps and hours, minutes and seconds, but that don't represent any particular date.
The previous functions return values that are incorrectly offset by 1 hour (3600 seconds) when you are in daylight savings time.
Here are revised functions that take into account whether or not you are on daylight savings time.
These 2 functions let you convert back and forth between human-readable H:M:S format and non-negative, GMT-agnostic (and DST-agnostic!!) timestamps for when you are working only with hours, minutes, and seconds.
<?php
function hms_2_ts($hms) {
$offset = date(Z); $is_dls = date(I) == 1 ? true : false; if($is_dls) $offset -= 3600; $hms_arr = explode(":", $hms);
$h = $hms_arr[0];
$m = $hms_arr[1];
$s = $hms_arr[2] + $offset; $ts = mktime($h, $m, $s, 1, 1, 1970, 0);
return $ts;
}
function ts_2_hms($ts)
{
$offset = date(Z);
$is_dls = date(I) == 1 ? true : false; if($is_dls) $offset -= 3600; $ts += 86400; $ts -= $offset; return date("H:i:s", $ts);
}
echo "offset = " . date(Z) . "<br>";
$hms = "00:00:01";
echo "hms = $hms<br>";
$ts = hms_2_ts($hms);
echo "ts = $ts<br>";
$hms_again = ts_2_hms($ts);
echo "hms again = $hms_again";
?>
I suggest that "Daylight Savings Time" could also be called "Programmers' Wasting Time" :)
webmaste at caleidosmultimedia dot com
27-Apr-2005 07:42
My little code for make a code to get the difference between dates
<?
$data1 = mktime (0,0,0,5,5,2005); $data2 = mktime (0,0,0,5,15,2005); $differenza = ($data2 - $data1 ) / 86400;
echo " The Different $data2 - data1 = $differenza";
?>
armando at scribano dot com dot ar
20-Apr-2005 04:12
This function return date (format d/m/Y) of N monday
$fechalunes1 = buscalunes($lunes='1');
function buscalunes($lunes)
{
//busca N lunes y da el dia
$fecha = date ("Ymd");
$ano = substr ($fecha,0, 4);
$mes = substr ($fecha,4, -2);
$dia = substr ($fecha,6,8);
$con=1;
while($contlunes!=$lunes)
{
$dia_chr = date( "l", mktime(0,0,0,$mes,$dia-$con,$ano));
if($dia_chr=='Monday')
{
$fechalunes = date( "d/m/Y", mktime(0,0,0,$mes,$dia-$con,$ano));
$contlunes++;
}
$con ++;
}
return $fechalunes ;
}
forums at jefferyfernandez dot id dot au
15-Apr-2005 10:33
With response to Robert Christiaanse's Delphi related convertion to find the
day in the week of a year, here is my solution
The original purpose of this function was to return the "first day of the week"
for a timesheet application. Since PHP defaults to Monday as the start of the
week, and the need for my app to have Sunday as the start of the week, I had to
pass the day as an argument. So if you call the function like:
find_first_day_ofweek(16, 2005, 'sunday');
it would return the unix timestamp of the Sunday in week 16 of 2005.
<?php
function find_first_day_ofweek($week, $year, $start_of_week='sunday')
{
$target_week = strtotime("$week week", strtotime("1 January $year"));
$date_info = getdate($target_week);
$day_of_week = $date_info['wday'];
switch (strtolower($start_of_week))
{
case 'sunday':
$adjusted_date = $day_of_week;
break;
case 'monday':
$adjusted_date = $day_of_week-1;
break;
case 'tuesday':
$adjusted_date = $day_of_week-2;
break;
case 'wednesday':
$adjusted_date = $day_of_week-3;
break;
case 'thursday':
$adjusted_date = $day_of_week-4;
break;
case 'friday':
$adjusted_date = $day_of_week-5;
break;
case 'saturday':
$adjusted_date = $day_of_week-6;
break;
default:
$adjusted_date = $day_of_week-1;
break;
}
$first_day = strtotime("-$adjusted_date day",$target_week);
return $first_day;
}
?>
colin dot horne at gmail dot com
31-Mar-2005 12:48
If the month is greater than 12, it goes into the next year. If it is less than 1, it goes into the previous year. Generally, it behaves as you'd expect it to :-)
Examples:
<?php
print date ("F j, Y", mktime (0,0,0,13,1,2004));
print date ("F j, Y", mktime (0,0,0,0,1,2004));
print date ("F j, Y", mktime (0,0,0,14,1,2004));
print date ("F j, Y", mktime (0,0,0,-1,1,2004));
?>
mariano at cricava dot com
26-Mar-2005 12:22
Here is another way to calculate the difference between two dates. It is based on previous date_diff example, but with the possibility now to specify full dates (dates plus time), and to get the result in different units.
Example of use:
<?php
$dateFrom = "25-03-2005 14:20:00";
$dateTo = date("d-m-Y H:i:s", strtotime('now'));
$diffd = getDateDifference($dateFrom, $dateTo, 'd');
$diffh = getDateDifference($dateFrom, $dateTo, 'h');
$diffm = getDateDifference($dateFrom, $dateTo, 'm');
$diffs = getDateDifference($dateFrom, $dateTo, 's');
$diffa = getDateDifference($dateFrom, $dateTo, 'a');
echo 'Calculating difference between ' . $dateFrom . ' and ' . $dateTo . ' <br /><br />';
echo $diffd . ' days.<br />';
echo $diffh . ' hours.<br />';
echo $diffm . ' minutes.<br />';
echo $diffs . ' seconds.<br />';
echo '<br />In other words, the difference is ' . $diffa['days'] . ' days, ' . $diffa['hours'] . ' hours, ' . $diffa['minutes'] . ' minutes and ' . $diffa['seconds'] . ' seconds.<br>';
?>
Here's the code:
<?php
function getDateDifference($dateFrom, $dateTo, $unit = 'd')
{
$difference = null;
$dateFromElements = split(' ', $dateFrom);
$dateToElements = split(' ', $dateTo);
$dateFromDateElements = split('-', $dateFromElements[0]);
$dateFromTimeElements = split(':', $dateFromElements[1]);
$dateToDateElements = split('-', $dateToElements[0]);
$dateToTimeElements = split(':', $dateToElements[1]);
$date1 = mktime($dateFromTimeElements[0], $dateFromTimeElements[1], $dateFromTimeElements[2], $dateFromDateElements[1], $dateFromDateElements[0], $dateFromDateElements[2]);
$date2 = mktime($dateToTimeElements[0], $dateToTimeElements[1], $dateToTimeElements[2], $dateToDateElements[1], $dateToDateElements[0], $dateToDateElements[2]);
if( $date1 > $date2 )
{
return null;
}
$diff = $date2 - $date1;
$days = 0;
$hours = 0;
$minutes = 0;
$seconds = 0;
if ($diff % 86400 <= 0) {
$days = $diff / 86400;
}
if($diff % 86400 > 0)
{
$rest = ($diff % 86400);
$days = ($diff - $rest) / 86400;
if( $rest % 3600 > 0 )
{
$rest1 = ($rest % 3600);
$hours = ($rest - $rest1) / 3600;
if( $rest1 % 60 > 0 )
{
$rest2 = ($rest1 % 60);
$minutes = ($rest1 - $rest2) / 60;
$seconds = $rest2;
}
else
{
$minutes = $rest1 / 60;
}
}
else
{
$hours = $rest / 3600;
}
}
switch($unit)
{
case 'd':
case 'D':
$partialDays = 0;
$partialDays += ($seconds / 86400);
$partialDays += ($minutes / 1440);
$partialDays += ($hours / 24);
$difference = $days + $partialDays;
break;
case 'h':
case 'H':
$partialHours = 0;
$partialHours += ($seconds / 3600);
$partialHours += ($minutes / 60);
$difference = $hours + ($days * 24) + $partialHours;
break;
case 'm':
case 'M':
$partialMinutes = 0;
$partialMinutes += ($seconds / 60);
$difference = $minutes + ($days * 1440) + ($hours * 60) + $partialMinutes;
break;
case 's':
case 'S':
$difference = $seconds + ($days * 86400) + ($hours * 3600) + ($minutes * 60);
break;
case 'a':
case 'A':
$difference = array (
"days" => $days,
"hours" => $hours,
"minutes" => $minutes,
"seconds" => $seconds
);
break;
}
return $difference;
}
?>
Romain Sam
25-Mar-2005 09:50
Under Windows, mktime goes until 2038-01-19 (03:14:07 ...)
Matt
24-Mar-2005 12:52
Just a note:
If month has a zero before it (IE '03'), mktime will not like it and give you an output of -1
Greg Robbins
14-Mar-2005 10:12
For a project I need to use "generic times" - just hours, minutes and seconds that don't represent any particular date.
I needed to convert human-readable H:M:S values to timestamp-like integers representing seconds (Example: 00:30:00 becomes 1800). The resulting values are very small; as a result, functions like mktime(), date() & friends think they're dealing with timestamps right around the Unix Epoch.
The problem is the Windows / GMT factor. For some values I got warnings about dates before January 1, 1970 not being accepted by Windows. Then other times I would get unexpected values because of my GMT offset (it happens in the best of families).
Here's 2 functions that should let you convert back and forth between human-readable H:M:S format and non-negative, GMT-agnostic timestamps for when you are working only with hours, minutes, and seconds.
<?php
function hms_2_ts($hms) {
$offset = date(Z); $hms_arr = explode(":", $hms);
$h = $hms_arr[0];
$m = $hms_arr[1];
$s = $hms_arr[2] + $offset; $ts = mktime($h, $m, $s, 1, 1, 1970, 0);
return $ts;
}
function ts_2_hms($ts)
{
$offset = date(Z);
$ts += 86400; $ts -= $offset; return date("H:i:s", $ts);
}
echo "offset = " . date(Z) . "<br>";
$hms = "00:00:01";
echo "hms = $hms<br>";
$ts = hms_2_ts($hms);
echo "ts = $ts<br>";
$hms_again = ts_2_hms($ts);
echo "hms again = $hms_again";
?>
maxnamara at yahoo dot com
08-Mar-2005 09:08
How to get the date of next day(s) ?
Please take a look my working code:
<?
function add_zero($a){
$b = $a;
if(strlen($a) == 1){
$b = "0".$a;
}
return $b;
}
function day_th($gmt, $no=30){
$d = explode(" ",$gmt);
$date = $d[0];
$time = $d[1];
$date_x = explode("-",$date);
$year = $date_x[0];
$month = $date_x[1];
$day = $date_x[2];
$time_x = explode(":",$time);
$hour = $time_x[0];
$minute = $time_x[1];
$second = $time_x[2];
$t = mktime($hour, $minute, $second, $month, $day, $year);
$unix_stamp = 86400 * $no;
$res = getdate($t + $unix_stamp);
$ris = array_values($res);
list($seconds,$minutes,$hours,$mday,$wday,$mon,$year,
$yday,$weekday,$month,$unix) = $ris;
$mon = add_zero($mon);
$mday = add_zero($mday);
$seconds = add_zero($seconds);
$minutes = add_zero($minutes);
$hours = add_zero($hours);
$day_th = $year."-".$mon."-".$mday." ".$hours.":".$minutes.":".$seconds;
return $day_th;
}
$gmt = "2005-02-28 00:00:01";
$nextdate = day_th($gmt, $no=1);
echo $gmt."<br>".$nextdate."<br>";
?>
maxnamara at yahoo dot com
08-Mar-2005 08:35
This is my way to get unix timestamp.
<?
$serverdate = gmstrftime("%Y-%m-%d %H:%M:%S");
echo $serverdate."<br>";
function extract_date($date){
$arr = explode(" ",$date);
$d = $arr[0];
$t = $arr[1];
$arr_d = explode("-",$d);
$year = $arr_d[0];
$year = intval($year);
$month = $arr_d[1];
$month = intval($month);
$day = $arr_d[2];
$day = intval($day);
$arr_t = explode(":",$t);
$hour = $arr_t[0];
$hour = intval($hour);
$minute = $arr_t[1];
$minute = intval($minute);
$second = $arr_t[2];
$second = intval($second);
return array($hour, $minute, $second, $month, $day, $year);
}
function unix_timestamp($date) {
$a = extract_date($date);
$b = mktime($a[0],$a[1],$a[2],$a[3],$a[4],$a[5]);
return $b;
}
echo "<br><br><br>";
echo "Unix TimeStamp:<br>";
$b = unix_timestamp($serverdate);
echo $b."<br>";
?>
the_boy_who_got_lost at yahoo dot com
07-Mar-2005 04:10
Just an example of how to get the date out of a couple of list boxes, for newbe's
<form action="<?=$PHP_SELF ?>" method="post">
<span class="row2"><select name="month" id="month">
<option selected="selected">Month</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
</select>
<select name="day" id="day">
<option selected="selected">Day</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
<option>11</option>
<option>12</option>
<option>13</option>
<option>14</option>
<option>15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
<option>21</option>
<option>22</option>
<option>23</option>
<option>24</option>
<option>25</option>
<option>26</option>
<option>27</option>
<option>28</option>
<option>29</option>
<option>30</option>
<option>31</option>
</select>
<select name="year" id="year">
<option selected="selected">Year</option>
<option>05</option>
<option>06</option>
</select>
<input name="submit" type="submit" id="submit" value="submit">
</span>
</form>
<?php
if (!isset($_POST['submit'])){
}
else {
$Dmonth = $_POST[month];
$Dday = $_POST[day];
$Dyear = $_POST[year];
if ($Dmonth == 'April') {$r = "4";}
elseif ($Dmonth == 'May') {$r = "5";}
elseif ($Dmonth == 'June') {$r = "6";}
elseif ($Dmonth == 'July') {$r = "7";}
elseif ($Dmonth == 'August') {$r = "8";}
elseif ($Dmonth == 'September') {$r = "9";}
elseif ($Dmonth == 'October') {$r = "10";}
echo "<br />";
echo "<br />";
$date1 = date("M-d-y", mktime(0, 0, 0, $r, $Dday, $Dyear));
echo $date1 ;
echo "<br />";
echo date("M-d-y", mktime(0, 0, 0, $r, ++$Dday, $Dyear));
echo "<br />";
echo date("M-d-y", mktime(0, 0, 0, $r, ++$Dday, $Dyear));
echo "<br />";
echo date("M-d-y", mktime(0, 0, 0, $r, ++$Dday, $Dyear));
}
?>
andreas dot schmeiler at rtlnewmedia dot de
11-Feb-2005 06:41
if you ever wondered how to convert a windows (ASP) Timestamp to an unix Timestamp, try this:
(windowsTime to unixTime):
function wT2uT($win_timestamp) {
$WIN_DATE_CONST=2209165200;
$WIN_TIME_CONST=115740.74074074;
list($win_date, $win_time)=explode(",",$win_timestamp);
$win_time=substr($win_time."0000000000",0,10);
$ux_date = $win_date*24*60*60;
$ux_date-= (date("I")*60*60);
$ux_date-= $WIN_DATE_CONST;
$ux_time = round($win_time/$WIN_TIME_CONST);
return($ux_date+$ux_time);
}
kwillmert a visionaryweb dt com
09-Feb-2005 04:47
A simpler version of the function below:
<?php
function dttm2unixtime( $dttm2timestamp_in )
{
list( $date, $time ) = split(" ", $dttm2timestamp_in);
list( $year, $month, $day ) = split( "-", $date );
list( $hour, $minute, $second ) = split( ":", $time );
return mktime( $hour, $minute, $second, $month, $day, $year );
}
?>
You don't need to run intval on each string, mktime knows what they are and will do that behind the scenes.
dasprid [AT] web [DOT] de
04-Feb-2005 06:42
I have to correct, what Evorg (28-Sep-2004 04:24) wrote. If you want to delete a cookie, simply take the value 0 (zero) as timestamp. It's the same as the timestamp, which Evorg's example generates.
fontajos at phpeppershop dot com
01-Dec-2004 04:19
<?php
function date_diff_value($days) {
$day_1_1_1970 = 719543;
$diff = $days - $day_1_1_1970;
$unix_ts = $diff * 86400;
return $unix_ts;
}
?>
cp at u-help dot org
27-Nov-2004 07:53
I once had to deal with dates coming in as a sting from a mysql database (surprise, surprise ;-)) without having any option to select anything differen (i.e. using mysql's UNIX_TIMESTAMP)
This caused me a lot of problems and I couldn't seem to find anything anywhere that would just take the entire lot as an input to convert it to unix-timestamp.
Maybe someone else finds the below function useful to convert these date/time strings into unix-timestamps
<?php
function dttm2unixtime($dttm2timestamp_in){
$date_time = explode(" ", $dttm2timestamp_in);
$date = explode("-",$date_time[0]);
$time = explode(":",$date_time[1]);
unset($date_time);
list($year, $month, $day)=$date;
list($hour,$minute,$second)=$time;
return mktime(intval($hour), intval($minute), intval($second), intval($month), intval($day), intval($year));
}
?>
A mysql date-time value like "2004-11-28 01:34:20" would be converted to this: 1101605660
As a verification, date("Y-m-d H:i:s", 1101605660) would return the same as the value passed in, i.e. 2004-11-28 01:34:20
Using the function above, you don't have to include any fancy parsing into the retrieval of the results...
hope it helps ;)
phpmanual at localpin dot com
02-Nov-2004 03:03
Daylight saving time! Grrrrrrrrrr! (And a minor "Grrr!" for PHP making this less intuitive than it should be).
In brief, NEVER add number of seconds, like 60*60*24, but use strtotime("+1 day", $myDate)).
Some of the 'simple' functions above for calculating dates will NOT work correctly when a date includes daylight saving time. Shown below is the problem illustrated and a simple solution.
EXAMPLE 1: WRONG!
I had the following loop, which worked fine all year, until this weekend, when the clocks changed, and it broke! The problem is daylight saving time:
// Loop through dates adding 1 days worth of seconds each time
$myDate = 1098914400 // October 28th
for ($myDate = $fromDate; $myDate <= $toDate; $myDate = $myDate + 60 * 60 * 24) {
$printable = strftime("%d-%m-%Y %H:%M:%S", $myDate);
echo $printable
}
"28-10-2004 00:00:00"
"29-10-2004 00:00:00"
"30-10-2004 00:00:00"
"31-10-2004 00:00:00"
"31-10-2004 23:00:00" (oops! 31st October repeats and time now 23:00!!)
"01-11-2004 23:00:00"
"02-11-2004 23:00:00"
EXAMPLE 2: CORRECT!
$myDate = 1098914400 // October 28th
for ($myDate = $fromDate; $myDate <= $toDate; $myDate = strtotime("+1 day", $myDate)) {
$printable = strftime("%d-%m-%Y %H:%M:%S", $myDate);
echo $printable
}
"28-10-2004 00:00:00"
"29-10-2004 00:00:00"
"30-10-2004 00:00:00"
"31-10-2004 00:00:00"
"01-11-2004 00:00:00"
"02-11-2004 00:00:00"
Evorg
28-Sep-2004 09:24
mktime should be used when removing cookies. Normally people tend to use: time()-3600 to set the expiration date in "the past". The problem with this is that some computers is set at a wrong date and therfore differs from the server-time. That will render the time()-3600 unusable.
Instead use mktime(12,0,0,1, 1, 1990) as you expiration criteria. I'm convinced that only a very few users has set their time back more than 1990 :)
alex at gameserverhost dot nl
14-Sep-2004 04:27
A simple statement to calculate days between two dates
$dayselepsed = round((strtotime($dateone) - strtotime($datetwo))/(60*60*24)-1);
Regards Alex Curvers
jlim at natsoft dot com dot my
25-Jun-2004 07:36
Hi,
For those looking for a solution to the 1970-2038 limitation, the adodb time library does the trick nicely. The website has changed, to
http://phplens.com/phpeverywhere/adodb_date_library
"This library replaces native functions as follows:
getdate() with adodb_getdate()
date() with adodb_date()
gmdate() with adodb_gmdate()
mktime() with adodb_mktime()
gmmktime() with adodb_gmmktime()"
Download the inc file:
http://phplens.com/lens/dl/adodb-time.zip
Enjoy, John Lim
noodle at digital-nw dot com
16-May-2004 09:47
If the time has passed and you have not specified a date, mktime will automatically move to the next date. For example:
$hour = '12';
$mins = '37';
$time = mktime($hour,$mins,0,date('n'),date('d'));
echo date("l dS of F Y h:i:s A",$time);
will return something like:
Monday 17th of May 2004 12:37:00 PM
When in actuality it's Sunday 16th of May.
Robert Christiaanse
14-May-2004 12:56
In addition to my post (get date by week number, day of the week and year)...
No Daylight saving was taken into account!!! That's were the 3600 --- It's summertime here now :-) --- is used for in PHPUnixTimeStamp(), but it's dirty and also wrong.
Robert Christiaanse
14-May-2004 12:47
If you want to get the date of a given day in a week, this might be useful. (I.e. you want to know what is the date of Friday in week 20 of 2004)
This code was converted from Delphi source code and has been tested. No guarantees however ;-)
<?php
$aWeek=20; $aDay=05; $aYear=2004;
$adate=datefromweeknr($aYear, $aWeek, $aDay);
echo 'The date (week='.$aWeek.' day='.$aDay.' year= '.$aYear.') is '.date('D d-m-Y',$adate).'<br>';
function datefromweeknr($aYear, $aWeek, $aDay)
{
$FirstDayOfWeek=1; $BaseDate=4; $CJDDelta=2415019; $StartDate = DelphiDate(mktime(1,0,0,01,$BaseDate,$aYear)); $Offset = ($aWeek-1) * 7 - mod(floor($StartDate) + $CJDDelta + 8 - $FirstDayOfWeek,7) + $aDay - 1;
return PHPUnixTimeStamp($StartDate + $Offset);
}
function DelphiDate($aPHPTime)
{
return div($aPHPTime,86400)+25569;
}
function PHPUnixTimeStamp($aDelphiDate)
{
return ($aDelphiDate-25569)*86400-3600;
}
function mod($number, $div)
{
return $number - floor($number/$div)*$div;
}
function div($number, $div)
{
return floor($number/$div);
}
?>
Dave J.
12-May-2004 10:42
bichinhoverde's my_gmmktime function uses an incomplete definition of leap year. It's not leap year if the year is divisible by 100 and NOT divisible by 400. E.G. 2000 was a leap year, but 2100 will not be. Trivial, but it should be said.
Thus,
if ( $i % 4 == 0 ) {
$output += 24*60*60;
}
should be:
if ( (($i % 4 == 0) && ($i % 100 != 0))
|| ($i % 400 == 0) ) {
$output += 24*60*60;
}
matt at killermookie dot org
22-Apr-2004 07:27
I noticed that while it is legal to do this:
$date=date("Y-m-d", mktime(0,0,0,4,20,2004);
It doesn't quite work the same when you do this:
$time=date("H:i:s", mktime(10,30,15,0,0,0);
No matter what variables you put in for time, it'll always spit out 15:59:59. You need to include the month, day and year if you want it to convert the time.
I spent nearly an hour trying to figure out what I was doing wrong til I stuck in a random date.
php at cNhOiSpPpAlMe dot org
22-Apr-2004 03:37
Is it DST in the US on/at $dDate? (Regional exceptions not included.)
Ref.: http://webexhibits.org/daylightsaving/e.html
I use this function to calculate time differences between a server located in the US and a region not affected by DST, and vice-versa.
<?
function f_IsDstUS ($dDate) {
$dApril1stDay = mktime(
0,0,0,
4,1,date("Y",$dDate));
$dApril1stSunday = $dApril1stDay
+((7-date("w",$dApril1stDay))%7)*(60*60*24);
$dDstStart = mktime(
2,0,0,
date("m",$dApril1stSunday),
date("d",$dApril1stSunday),
date("Y",$dApril1stSunday));
$dOctoberLastDay = mktime(
0,0,0,
11,0,date("Y",$dDate));
$dOctoberLastSunday = $dOctoberLastDay
-(date("w",$dOctoberLastDay))*(60*60*24);
$dDstEnd = mktime(
2,0,0,
date("m",$dOctoberLastSunday),
date("d",$dOctoberLastSunday),
date("Y",$dOctoberLastSunday));
return intval( $dDate >= $dDstStart
&& $dDate < $dDstEnd);
}
?>
y4yh00 at yahoo dot com
07-Apr-2004 06:58
php_manual at it-rex dot nl
28-Mar-2004 07:48
I found that using the mktime override function of rickenmeer at hotmail dot com like so:
mktime(0, 0, 0, 1, 1, 1970);
returned -3600 instead of 0, because the standard mktime function gets used for 1970 and above.
changing the line
if ($year >= 1970) return mktime ($hour, $minute, $second, $month, $date, $year);
to
if ($year > 1970) return mktime ($hour, $minute, $second, $month, $date, $year);
solves this (if you're only working with dates, ie. not using time), because the mktime function will not be used around the 'sensitive' area of 1970.
I guess it has something to do with daylight savings time or timezone correction (I'm in GMT +1 myself), but I haven't tested exhaustively.
joakim stai
28-Mar-2004 12:48
As Nigel pointed out, you should be aware of DST (Daylight Savings Time) when using mktime(). Some systems will return a negative value if you use 0 as the hour, as it will simply skip from (for example) 23:59:59 to 01:00:00. Instead use 12 (noon) as the hour and you won't get a negative timestamp or a date in the 1960's.
This code will work with DST:
$today = mktime(12, 0, 0, date("m"), date("d"), date("Y"));
ed_isthmus at NOSPAMyahoo dot com
08-Mar-2004 08:23
Further to a point iain made earlier, about problems with daylight savings time:
<?php
$timestamp = mktime(0, 0, 0, 3, 28, 2004);
echo date('d M Y H:i:s', $timestamp);
?>
Will output '27 Mar 2004 23:00:00' (in the UK)!
Best solution for me was to specify the dst argument:
<?php
$timestamp = mktime(0, 0, 0, 3, 28, 2004, 0);
?>
Alternatively, you could use gmmktime(); and/or check the timezone offset.
pb at _remove_ pedal dot dk
28-Feb-2004 09:30
I find it easiest, if I want to find you how many days there are between two dates to use the following method:
$init_day = 1;
$init_mth = 1;
$init_yr = 2004;
$dst_day = 5;
$dst_mth = 8;
$dst_yr = 2004;
//first convert to unix timestamp
$init_date = mktime(12,0,0,$init_mth,$init_day,$init_yr);
$dst_date = mktime(12,0,0,$init_mth,$init_day,$init_yr);
$offset = $dst_date-$init_date; //Depending on which offset type you want, switch order
$days = floor($offset/60/60/24);
Nigel Gilbert
15-Feb-2004 02:15
Several posts here offer procedures to compute the number of days between two dates based on using mktime, using the given date and 00:00:00 as the time. It turns out that this is bad choice for the default time for such calculations when the date in question happens to be the date when daylight savings time starts. For example, on several OSs, there is no such time as 00:00:00 30-03-2003 (and mktime returns a negative value), because the clock changed from 23:59:59 29-03-2003 straight to 01:00:00 30-03-2003 as a result of Daylight Saving. At better choice is to use, for example, 12,0,0,30,3,2003 as the argument to mktime, that is, use noon, not midnight as the default time.
web at nihongo dot d2g dot com
08-Feb-2004 03:13
<?php
function date_diff($date_from,$date_to,$unit='d')
{
$date_from_parts = explode('-', $date_from);
$date_to_parts = explode('-', $date_to);
$day_from = $date_from_parts[0];
$mon_from = $date_from_parts[1];
$year_from = $date_from_parts[2];
$day_to = $date_to_parts[0];
$mon_to = $date_to_parts[1];
$year_to = $date_to_parts[2];
$sign=1;
if ($year_from>$year_to) $sign=-1;
else if ($year_from==$year_to)
{
if ($mon_from>$mon_to) $sign=-1;
else if ($mon_from==$mon_to)
if ($day_from>$day_to) $sign=-1;
}
if ($sign==-1) {$day_from = $date_to_parts[0];
$mon_from = $date_to_parts[1];
$year_from = $date_to_parts[2];
$day_to = $date_from_parts[0];
$mon_to = $date_from_parts[1];
$year_to = $date_from_parts[2];
}
switch ($unit)
{
case 'd': case 'D': $yearfrom1=$year_from; $yearto1=$year_to; if ($yearfrom1<1980)
{$deltafrom=-floor((1999-$yearfrom1)/20)*20; $yearfrom2=$yearfrom1-$deltafrom; }
else if($yearfrom1>1999)
{$deltafrom=floor(($yearfrom1-1980)/20)*20; $yearfrom2=$yearfrom1-$deltafrom; }
else {$deltafrom=0;
$yearfrom2=$yearfrom1;
}
if ($yearto1<1980) {$deltato=-floor((1999-$yearto1)/20)*20; $yearto2=$yearto1-$deltato; }
else if($yearto1>1999) {$deltato=floor(($yearto1-1980)/20)*20; $yearto2=$yearto1-$deltato; }
else {$deltato=0;
$yearto2=$yearto1;
}
$ts_from = mktime(0, 0, 0, $mon_from, $day_from, $yearfrom2);
$ts_to = mktime(0, 0, 0, $mon_to, $day_to, $yearto2);
$diff = ($ts_to-$ts_from)/86400;
$diff += 7305 * (($deltato-$deltafrom) / 20);
return $sign*$diff;
break;
case 'y': case 'Y': $diff=$year_to-$year_from;
$adjust=0;
if ($mon_from>$mon_to) $adjust=-1;
else if ($mon_from==$mon_to)
if ($day_from>$day_to) $adjust=-1;
return $sign*($diff+$adjust);
break;
}
}
?>
praas at NOSPAM dot ision dot nl
01-Feb-2004 02:44
Consider skipping months with mktime().
$nextmonth = date("M",mktime(0,0,0,date("n")+1,date("j"),date("Y")));
On any day in Januari you expect to get Feb, right?
But on January 30th you'll get Mar. It will try Feb 30th, which doesn't exist, and skips another month. Therefore in this case present a day value that will certainly be legal in any month, like day "1".
This will give you next month on any day of the year:
$nextmonth = date("M",mktime(0,0,0,date("n")+1,1,date("Y")));
thomas is at xenocast
27-Jan-2004 02:09
I found that the maketime() function below worked better for pre-1970 dates than did the &mktime() function just two down from here.
When testing for March 26, 1952 The &mktime() function produced the date but the time was 19:00 whereas maketime() did it properly at midnight.
marcbs78 at gmx dot net
20-Jan-2004 08:43
The function MakeTime() of todd at buiten dot com does work very well but there is al little problem with the introduction of summer/winter time.
In Germany this time is introduced in 1980. So if we shift the timezone from 1952-1969 to 1980-1997 you'll work with summer/winter time but this isn't correct.
This doesn't matter until you'll work only with dates. If you do, you're loosing one hour which means in dates this is one day which is lost.
rickenmeer at hotmail dot com
12-Jan-2004 08:30
<?PHP
function &mktime ($hour = false, $minute = false, $second = false, $month = false, $date = false, $year = false)
{
if ($hour === false) $hour = Date ("G");
if ($minute === false) $minute = Date ("i");
if ($second === false) $second = Date ("s");
if ($month === false) $month = Date ("n");
if ($date === false) $date = Date ("j");
if ($year === false) $year = Date ("Y");
if ($year >= 1970) return mktime ($hour, $minute, $second, $month, $date, $year);
$m_days = Array (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
if ($year % 4 == 0 && ($year % 100 > 0 || $year % 400 == 0))
{
$m_days[1] = 29; }
$d_year = 1970 - $year;
$days = 0 - $d_year * 365;
$days -= floor ($d_year / 4); $days += floor (($d_year - 70) / 100); $days -= floor (($d_year - 370) / 400); for ($i = 1; $i < $month; $i++)
{
$days += $m_days [$i - 1];
}
$days += $date - 1;
$stamp = $days * 86400;
$stamp += $hour * 3600;
$stamp += $minute * 60;
$stamp += $second;
return $stamp;
}
?>
iain at seatofthepants dot net
08-Dec-2003 09:49
In the above example it should ne boted that if you try to calculate the command at midnight on the 28/04/2004 you will get an erroneous response. This has been driving me to distraction.
$myTime = mktime( 0, 0, 0, 3, 28, 2004);
Solution I found was to create the time at 3am well after the 2am daylight savings problem, viz:
$myTime = mktime( 3, 0, 0, 3, 28, 2004);
Not sure if this is documented anywhere.
todd at buiten dot com
07-Dec-2003 03:14
If you want to calculate dates before 1970 and your OS doesn't support it (Windows and Linux), you can easily write your own wrapper to mktime to do the calculation. The idea is to find a date range in the 1970-2037 time frame that is the same as your year prior to 1970 (both years start on the same day of the week and leap years are the same), then add that number of years to your year value before calling mktime() and then subtract the corresponding number of seconds from the mktime() result (including the appropriate number of leap seconds). This way old guys like me (born in 1963) can get a valid number back from mktime() and we can figure out how old we are in seconds. :-) You can go all the way back to 1902 if you want.
The mapping is as follows:
1902-1951 = 1986-2035
1952-1969 = 1980-1997
By matching starting day of week for the year and leap years then we should calculate daylight time correctly (assuming that we have the right rules set). There's a special hack in the code to turn off daylight time prior to 1942 for date().
Here's the code that we're using now:
//
// Replacement for mktime that does dates before 1970
//
function MakeTime()
{
$objArgs = func_get_args();
$nCount = count($objArgs);
if ($nCount < 7)
{
$objDate = getdate();
if ($nCount < 1)
$objArgs[] = $objDate["hours"];
if ($nCount < 2)
$objArgs[] = $objDate["minutes"];
if ($nCount < 3)
$objArgs[] = $objDate["seconds"];
if ($nCount < 4)
$objArgs[] = $objDate["mon"];
if ($nCount < 5)
$objArgs[] = $objDate["mday"];
if ($nCount < 6)
$objArgs[] = $objDate["year"];
if ($nCount < 7)
$objArgs[] = -1;
}
$nYear = $objArgs[5];
$nOffset = 0;
if ($nYear < 1970)
{
if ($nYear < 1902)
return 0;
else if ($nYear < 1952)
{
$nOffset = -2650838400;
$objArgs[5] += 84;
// Apparently dates before 1942 were never DST
if ($nYear < 1942)
$objArgs[6] = 0;
}
else
{
$nOffset = -883612800;
$objArgs[5] += 28;
}
}
return call_user_func_array("mktime", $objArgs) + $nOffset;
}
In Linux, the values returned will work just fine with date() and I believe that strftime() should work too, but Windows doesn't like the negative values at all. We had to write a replacement for strtotime since it appears to call mktime() to come up with the final result.
I hope that this helps someone.
- todd
verszuz at hotmail dot com
28-Nov-2003 11:53
I figured out this way to calculate your age using mktime:
<?php
$day=27;$month=10;$year=1977;$now=mktime();
echo $now."<br>";
$timebirth=mktime(0,0,0,$month,$day,$year);
echo $timebirth."<br>";
$agetime=$now-$timebirth;
echo ((strftime("%Y",$agetime))-(strftime("%Y",0)));
?>
I hope this will help. Remember this calculator does not work properly on windows because of the limited range of mktime().
sun4php at coolguide dot net
24-Nov-2003 07:36
Very often we are faced with the problem of adjusting ourself to local time where application is running rather than running our application at server time.
Now we have a way to do that by setting TZ variable using putenv() method. But due to the non-availability of standard time zone codes, developers are often faced with the ambiguity of how to implement a non standard time zone(those which are not too popular)
I figured a way out myself for this. It uses the information that a particular time zone is n hours ahead or n hours behind standard GMT time zone.
here is what i did.
<?php
$day=15;
$month=12;
$year=2003;
$deadline=mktime('','','',$month,$day,$year);
$hour=gmdate('H');
$min=gmdate('i');
$sec=gmdate('s');
$month=gmdate('n');
$day=gmdate('d');
$year=gmdate('Y');
$stamp=mktime ($hour,$min,$sec,$month,$day,$year);
$do=6*60*60;
$lstamp=$stamp-$do;
echo("Today(local date/Central):".date('h:i:s d/n/Y',$lstamp)."<br>");
$left=$deadline-$lstamp;
$days_left=floor($left/(24 * 60 * 60));
$hours_left=floor($left/(60 * 60 ));
echo "<br>Days Left: $days_left<br>";
echo "<br>Hours Left(approx): $hours_left<br>";
?>
Change the $do variable to whatever seconds you are different from GMT and add or subtract accordingly to generate $lstamp.
This would solve your time zone problems.
Happy Coding,
Suneel Kanuri
trahma
20-Nov-2003 02:06
I think it is important to note that the timestamp returned is based upon the number of seconds from the epoch GMT, and then modified by the time zone settings on the server.
Thus...
mktime(0,0,0,1,1,1970) will not always return 0. For example with the US eastern time zone (GMT-5) will return 18000 (5 hours past the epoch) and the same function with the time zone set to the US pacific time zone (GMT-8) will return 28800 (8 hours past the epoch).
In an instance where you want time zone independence, you should use the function gmmktime()
laurie at oneuponedown dot com
18-Nov-2003 10:42
With regard to Example 1 and using mktime to correct out-of-range input.
It should be noted that mktime will implement day light saving amends. Consider the following:
<?
print(date("d/m/Y H:i:s",mktime(0,0,0,3,(27 + 1),2004)));
?>
OUTPUT "28/03/2004 02:00:00"
<?
print(date("d/m/Y H:i:s",(mktime(0,0,0,3,27,2004) + (((1 * 24) * 60) * 60))));
?>
OUTPUT "28/03/2004 00:00:00"
Dependent on your requirements this may or may be desirable
| |