PHP
downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

strftime> <microtime
Last updated: Fri, 03 Jul 2009

view this page in

mktime

(PHP 4, PHP 5)

mktimeGet Unix timestamp for a date

Description

int mktime ([ int $hour= date("H") [, int $minute= date("i") [, int $second= date("s") [, int $month= date("n") [, int $day= date("j") [, int $year= date("Y") [, int $is_dst= -1 ]]]]]]] )

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.

Parameters

hour

The number of the hour.

minute

The number of the minute.

second

The number of seconds past the minute.

month

The number of the month.

day

The number of the day.

year

The number of the year, may be a two or four digit value, with values between 0-69 mapping to 2000-2069 and 70-100 to 1970-2000. 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. However, before PHP 5.1.0 this range was limited from 1970 to 2038 on some systems (e.g. Windows).

is_dst

This parameter 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: As of PHP 5.1.0, this parameter became deprecated. As a result, the new timezone handling features should be used instead.

Return Values

mktime() returns the Unix timestamp of the arguments given. If the arguments are invalid, the function returns FALSE (before PHP 5.1 it returned -1).

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 or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version Description
5.3.0 mktime() now throws E_DEPRECATED notice if the is_dst parameter is used.
5.1.0 The is_dst parameter became deprecated. Made the function return FALSE on error, instead of -1. Fixed the function to accept the year, month and day to be all passed as zero.
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example #1 mktime() basic example

<?php
// Set the default timezone to use. Available as of PHP 5.1
date_default_timezone_set('UTC');

// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " date("l"mktime(000712000));

// Prints something like: 2006-04-05T01:02:03+00:00
echo date('c'mktime(123452006));
?>

Example #2 mktime() example

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".

<?php
echo date("M-d-Y"mktime(00012321997));
echo 
date("M-d-Y"mktime(0001311997));
echo 
date("M-d-Y"mktime(000111998));
echo 
date("M-d-Y"mktime(0001198));
?>

Example #3 Last day of next month

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".

<?php
$lastday 
mktime(000302000);
echo 
strftime("Last day in Feb 2000 is: %d"$lastday);
$lastday mktime(0004, -312000);
echo 
strftime("Last day in Feb 2000 is: %d"$lastday);
?>

Notes

Caution

Before PHP 5.1.0, negative timestamps were not supported under any known version of Windows and some other systems as well. Therefore the range of valid years was limited to 1970 through 2038.

See Also

  • gmmktime() - Get Unix timestamp for a GMT date
  • date() - Format a local time/date
  • time() - Return current Unix timestamp



strftime> <microtime
Last updated: Fri, 03 Jul 2009
 
add a note add a note User Contributed Notes
mktime
lucianoiw at hotmail dot com
13-Mar-2009 01:48
Convert timestamp to time();

<?php
function wp_mktime($_timestamp = ''){
    if(
$_timestamp){
       
$_split_datehour = explode(' ',$_timestamp);
       
$_split_data = explode("-", $_split_datehour[0]);
       
$_split_hour = explode(":", $_split_datehour[1]);

        return
mktime ($_split_hour[0], $_split_hour[1], $_split_hour[2], $_split_data[1], $_split_data[2], $_split_data[0]);
    }
}
?>

[NOTE BY danbrown AT php DOT net: See also (http://php.net/strtotime)]
admin at stipe dot info
16-Feb-2009 10:12
With combination of mktime and getDate and date() you can add hours / seconds / days / months / years to ANY timestamp. Use strtotime() function to convert any type of dates to timestamp

<?php
   
public function addMonthToDate($timeStamp, $totalMonths=1){
       
// You can add as many months as you want. mktime will accumulate to the next year.
       
$thePHPDate = getdate($timeStamp); // Covert to Array   
       
$thePHPDate['mon'] = $thePHPDate['mon']+$totalMonths; // Add to Month   
       
$timeStamp = mktime($thePHPDate['hours'], $thePHPDate['minutes'], $thePHPDate['seconds'], $thePHPDate['mon'], $thePHPDate['mday'], $thePHPDate['year']); // Convert back to timestamp
       
return $timeStamp;
    }
   
    public function
addDayToDate($timeStamp, $totalDays=1){
       
// You can add as many days as you want. mktime will accumulate to the next month / year.
       
$thePHPDate = getdate($timeStamp);
       
$thePHPDate['mday'] = $thePHPDate['mday']+$totalDays;
       
$timeStamp = mktime($thePHPDate['hours'], $thePHPDate['minutes'], $thePHPDate['seconds'], $thePHPDate['mon'], $thePHPDate['mday'], $thePHPDate['year']);
        return
$timeStamp;
    }

    public function
addYearToDate($timeStamp, $totalYears=1){
       
$thePHPDate = getdate($timeStamp);
       
$thePHPDate['year'] = $thePHPDate['year']+$totalYears;
       
$timeStamp = mktime($thePHPDate['hours'], $thePHPDate['minutes'], $thePHPDate['seconds'], $thePHPDate['mon'], $thePHPDate['mday'], $thePHPDate['year']);
        return
$timeStamp;
    }
?>
ronnie dot kurniawan at gmail dot com
16-Jan-2009 05:49
Add (and subtract) unixtime:

<?php
function utime_add($unixtime, $hr=0, $min=0, $sec=0, $mon=0, $day=0, $yr=0) {
 
$dt = localtime($unixtime, true);
 
$unixnewtime = mktime(
     
$dt['tm_hour']+$hr, $dt['tm_min']+$min, $dt['tm_sec']+$sec,
     
$dt['tm_mon']+1+$mon, $dt['tm_mday']+$day, $dt['tm_year']+1900+$yr);
  return
$unixnewtime;
}
?>
electriic ink
17-Dec-2008 07:30
Days until Christmas:

<?php
     $time
= mktime(0, 0, 0, 12, 25, 2008, 1) - time();

    
$days = floor($time/86400);
    
$hours = floor(($time-($days*86400))/3600);
    
$mins = floor (($time-($days*86400)-($hours*3600))/60);
    
$secs = floor ($time-($days*86400)-($hours*3600)-($mins*60));

    
$tsecs = $time;
    
$thours = round($time/3600);

    
     if (
$tsecs <= 600) {

      echo
'<html> <head> <title> ' . $tsecs . ' seconds left until 12am Christmas Day </title> <meta http-equiv="refresh" content="1;url=""></head> <body><span

style="font-size:10pt">Christmas day in '
. $days . ' days ' . $hours . ' hours ' $mins . ' mins ' . $secs . ' seconds!<br><br>(There are ' . $tsecs . ' seconds in

total)</span></body></html>'
;
   
     } else {

      echo
'<html> <head> <title> ' . $thours . ' hours left until 12am Christmas Day </title> <meta http-equiv="refresh" content="10;url=""></head> <body><span

style="font-size:10pt">Christmas day in '
. $days . ' days ' . $hours . ' hours ' $mins . ' mins ' . $secs . ' seconds!<br><br>(There are ' . number_format($thours)

.
' hours in total and ' . number_format($tsecs) . ' seconds in total)</span></body></html>';

     }

?>
Alan
18-Nov-2008 03:52
Do remember that, counter-intuitively enough, the arguments for month and day are inversed (or middle-endian). A common mistake for Europeans seems to be to feed the date arguments in the expected order (big endian or little endian).

It's clear to see where this weird order comes from (even with the date being big endian the order for all arguments would still be mixed - it's obviously based on the American date format with the time "prefixed" to allow an easier shorthand) and why this wasn't changed (passing the values in the wrong order produces a valid, though unexpected, result in most cases), but it continues to be a source of confusion for me whenever I come back to PHP from other languages or libraries.
Anonymous
14-Nov-2008 04:34
<?php
//example of functions to know if a date/time value is in summer hour or in winter hour

//====================
function getChgWinDate($dt){
 
$y=substr($dt,0,4);
 for(
$i=31;$i>20;$i--){
 
$ts=mktime(3,0,0,10,$i,$y);
 
$dy=date('D',$ts);
  if(
$dy=='Sun') return($y.'/10/'.$i.' 03:00:00');
 }
}
//====================
function getChgSumDate($dt){
 
$y=substr($dt,0,4);
 for(
$i=31;$i>20;$i--){
 
$ts=mktime(2,0,0,10,$i,$y);
 
$dy=date('D',$ts);
  if(
$dy=='Sun') return($y.'/03/'.$i.' 02:00:00');
 }
}
//====================
function isSummerDate($dt){
 
$b1=getChgWinDate($dt);
 
$b2=getChgSumDate($dt);
 if(
$dt>=$b2&&$dt<$b1) return(true);
 return(
false);
}
//====================
function isWinterDate($dt){
 return(!
isSummerDate($dt));
}

//====================
$dt = '2008/10/26 03:15:16';
if(
isSummerDate($dt) ){
 echo
$dt . " is summer hour in france";
}else{
 echo
$dt . " is winter hour in france";
}
?>
thebloodyharry at gmail dot com
11-Nov-2008 02:04
here simple sample for timestamps.(using malaysia GMT 8)

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

$todaydate=date("(d/m/y) H:i:s", $mkendtimep);
if (date("l")=="Monday") { $mday=Monday; } else
    if (date("l")=="Tuesday") { $mday=Tuesday; } else
    if (date("l")=="Wednesday") { $mday=Wednesday; } else
    if (date("l")=="Thursday") { $mday=Thursday; } else
    if (date("l")=="Friday") { $mday=Friday; } else
    if (date("l")=="Saturday") { $mday=Saturday; } else
    if (date("l")=="Sunday"){  $mday=Sunday; }

$realtime="$mday$todaydate (GMT +8)";

..hope it will help you out....
yan
10-Nov-2008 01:50
caculate days between two date

<?php
 
// end date is 2008 Oct. 11 00:00:00
 
$_endDate = mktime(0,0,0,11,10,2008);
 
// begin date is 2007 May 31 13:26:26
 
$_beginDate = mktime(13,26,26,05,31,2007);

 
$timestamp_diff= $_endDate-$_beginDate +1 ;
 
// how many days between those two date
 
$days_diff = $timestamp_diff/86400;

?>
Maffu
29-Oct-2008 11:05
When calling mktime(), be sure that you use values without leading zeros.  The date comes out wrong in the following example:

$endts = mktime(12, 00, 00, 12, 08, 2008, 0);

(note the 08 instead of just 8)

C's scanf() has a format specification where leading 0's can indicate an octal value - perhaps this is related?
mark at markfiend dot com
15-Oct-2008 11:52
zola at zolaweb:

Your expression date('U', strtotime($mydate)) evaluates to strtotime($mydate). Converting to a UNIX timestamp is what strtotime() does.
ionut dot bodea at eydos dot ro
02-Oct-2008 03:29
Here is what I use to calculate age. It took me 30 minutes to write and it's quite accurate. What it has special is that it's calculating the number of days a year has (float number), by testing if a year is a leap one or not. This number is used to compute the age.

<?php
function get_age($date_start, $date_end) {
   
$t_lived = get_timestamp($date_end) - get_timestamp($date_start);
   
$seconds_one_year = get_days_per_year($date_start, $date_end) * 24 * 60 * 60;
   
$age = array();
   
$age['years_exact'] = $t_lived / $seconds_one_year;
   
$age['years'] = floor($t_lived / $seconds_one_year);
   
$seconds_remaining = $t_lived % $seconds_one_year;
   
$age['days'] = round($seconds_remaining / (24 * 60 * 60));
    return
$age;
}
function
get_timestamp($date) {
    list(
$y, $m, $d) = explode('-', $date);
    return
mktime(0, 0, 0, $m, $d, $y);
}
function
get_days_per_year($date_start, $date_end) {
    list(
$y1) = explode('-', $date_start);
    list(
$y2) = explode('-', $date_end);
   
$years_days = array();
    for(
$y = $y1; $y <= $y2; $y++) {
       
$years_days[] = date('L', mktime(0, 0, 0, 1, 1, $y)) ? 366 : 365;
    }
    return
round(array_sum($years_days) / count($years_days), 2);
}

$date_birth = '1979-10-12';
$date_now = date('Y-m-d');

$age = get_age($date_birth, $date_now);
echo
'<pre>';
print_r($age);
echo
'</pre>';
?>


It will display something like this:
Array
(
    [years_exact] => 28.972974329491
    [years] => 28
    [days] => 355
)
Anonymous
02-Oct-2008 12:28
Don't know about others, but this makes more sense to me:

<?php
function dateserial($year,$month,$day,$hour,$minute,$timezone = "UTC") {
   
$orgTZ = date_default_timezone_get();
   
date_default_timezone_set($timezone);
   
$retval = mktime($hour,$minute,0,$month,$day,$year);
   
date_default_timezone_set($orgTZ);
    return
$retval;
}
?>

The order makes more sense and the timezone defaults to UTC unless otherwise specified. The fact that you have to set the timezone gives you more control and forces you to be aware of it.
zola at zolaweb dot com
27-Sep-2008 08:27
You can't use something along the lines of

$mydate = '2008-27-09 3:52:06';
$x = mktime(date("Y", $mydate), date("m", $mydate), date("d", $mydate),  date("H", $mydate), date("i", $mydate), date("s", $mydate));

because mktime will puke on the leading zeroes, you'll get "Notice: A non well formed numeric value encountered in ...."

There's no setting to get seconds without leading zeros, at least not yet, so you have to prepare your date string first.

You can explode your date as some examples have shown, and then either multiply each result by 1 to remove the leading zero, or trim them off, but even simpler is to convert to the unix epoch:

$convert_date = date('U', strtotime($mydate));

You can add or subtract time in the ordinary way

$convert_date = date('U', strtotime("+1 day", $mydate));

and then convert it back to your preferred dateformat without invoking mktime at all.

$mynewdate = date('Y-m-d H:i:s', $convert_date);
 
Hopefully this will be useful if you are trying to calculate from an already formatted date, such as one grabbed from a database or mail.
domi at lab-9 dot com
16-Sep-2008 07:27
[quote thomas_corthals at hotmail dot com]
It seems mktime() doesn't return negative timestamps on Linux systems with a version of glibc <= 2.3.3.
[/quote]

Negative timestamps are not supported in any known Windows environment. Therefore only valuations for year in range of [1970..2038] are allowed. Thus you cannot rely that php knows how to handle negative timestamps. If you have valuations with year out of [1970..2038] you may got to think of a alternative implementation using date() and parse variables for yourself OR (which would be much faster) a self-designed class that safely calculates dates out of range.
ooogla at hotmail dot com
01-Sep-2008 10:56
If you want to increment the day based on a variable when using a loop you can use this when you submit a form

1. Establish a start date and end date in two different variables

2. Get the number of days between a date

$ndays = (strtotime($_POST['edate']) - strtotime($_POST['sdate'])) / (60 * 60 * 24);

Then here is the string you slip in your loop

$nextday  = date('Y-m-d', mktime(0, 0, 0, date("m", strtotime($_POST['sdate']))  , date("d", strtotime($_POST['sdate']))+ $count, date("Y", strtotime($_POST['sdate']))));

$count is incremented by the loop.
thomas_corthals at hotmail dot com
13-May-2008 02:34
It seems mktime() doesn't return negative timestamps on Linux systems with a version of glibc <= 2.3.3.
joseph dot andrew dot hughes at gmail dot com
30-Jan-2008 08:58
Just a small thing to think about if you are only trying to pull the month out using mktime and date.  Make sure you place a 1 into day field.  Otherwise you will get incorrect dates when a month is followed by a month with less days when the day of the current month is higher then the max day of the month you are trying to find.. (Such as today being Jan 30th and trying to find the month Feb.)
PHPcoder at freemail dot ig3 dot net
06-Sep-2007 05:58
The maximum possible date accepted by mktime() and gmmktime() is dependent on the current location time zone.

For example, the 32-bit timestamp overflow occurs at 2038-01-19T03:14:08+0000Z.  But if you're in a UTC -0500 time zone (such as EST in North America), the maximum accepted time before overflow (for older PHP versions on Windows) is 2038-01-18T22:14:07-0500Z, regardless of whether you're passing it to mktime() or gmmktime().
Jonathan Woodard
31-Aug-2007 02:31
NB: one 'gotcha' with the implementation of mktime()'s parameters:

<?php
for( $i = 1 $i <= 12 ; $i++ )
{
    echo
"Month '$i' is: " . date( "F" , mktime( 0 , 0 , 0 , $i ) ) . "\n";
}
?>
Will output:
Month '1' is: January
Month '2' is: March
Month '3' is: March
Month '4' is: May
Month '5' is: May
Month '6' is: July
Month '7' is: July
Month '8' is: August
Month '9' is: October
Month '10' is: October
Month '11' is: December
Month '12' is: December
on the 31st day of every month.

Why? Because the 5th parameter "day" defaults to "right now," which will not work reliably for days after the 28th.

To make sure this doesn't happen, specify the first day of the month:
<?php
mktime
( 0 , 0 , 0 , $i , 1 )
?>
rlz
17-Jul-2007 04:52
Finding out the number of days in a given month and year, accounting for leap years when February has more than 28 days.

<?php
function days_in_month($year, $month) {
    return(
date( "t", mktime( 0, 0, 0, $month, 1, $year) ) );
}
?>

Hope it helps a soul out there.
mike at mike-griffiths dot co dot uk
11-Jul-2007 01:04
It may be useful to note that no E_WARNINGS or E_NOTICES are give if you specify a date <1901 or >2038 on systems where time_t is a 32bit signed integer.

If a date is specified outside of the allowed range you may get some unexpected results as no timestamp will be returned.
rga at merchantpal dot com
31-Mar-2007 04:46
You cannot simply subtract or add month VARs using mktime to obtain previous or next months as suggested in previous user comments (at least not with a DD > 28 anyway).

If the date is 03-31-2007, the following yeilds March as a previous month. Not what you wanted.

<?php
$dateMinusOneMonth
= mktime(0, 0, 0, (3-1), 312007 );
$lastmonth = date("n | F", $dateMinusOneMonth);
echo
$lastmonth;    //---> 3 | March
?>

mktime correctly gives you back the 3rd of March if you subtract 1 month from March 31 (there are only 28 days in Feb 07).

If you are just looking to do month and year arithmetic using mktime, you can use general days like 1 or 28 to do stuff like this:

<?php
$d_daysinmonth
= date('t', mktime(0,0,0,$myMonth,1,$myYear));     // how many days in month
$d_year = date('Y', mktime(0,0,0,$myMonth,1,$myYear));        // year
$d_isleapyear = date('L', mktime(0,0,0,$myMonth,1,$myYear));    // is YYYY a leapyear?

$d_firstdow = date('w', mktime(0,0,0,$myMonth,'1',$myYear));     // FIRST falls on what day of week (0-6)
$d_firstname = date('l', mktime(0,0,0,$myMonth,'1',$myYear));     // FIRST falls on what day of week Full Name

$d_month = date('n', mktime(0,0,0,$myMonth,28,$myYear));         // month of year (1-12)
$d_monthname = date('F', mktime(0,0,0,$myMonth,28,$myYear));         // Month Long name (July)
$d_month_previous = date('n', mktime(0,0,0,($myMonth-1),28,$myYear));         // PREVIOUS month of year (1-12)
$d_monthname_previous = date('F', mktime(0,0,0,($myMonth-1),28,$myYear));     // PREVIOUS Month Long name (July)
$d_month_next = date('n', mktime(0,0,0,($myMonth+1),28,$myYear));         // NEXT month of year (1-12)
$d_monthname_next = date('F', mktime(0,0,0,($myMonth+1),28,$myYear));         // NEXT Month Long name (July)
$d_year_previous = date('Y', mktime(0,0,0,$myMonth,28,($myYear-1)));        // PREVIOUS year
$d_year_next = date('Y', mktime(0,0,0,$myMonth,28,($myYear+1)));        // NEXT year

$d_weeksleft = (52 - $d_weekofyear);                     // how many weeks left in year
$d_daysinyear = $d_isleapyear ? 366 : 365;                // set correct days in year for leap years
$d_daysleft = ($d_daysinyear - $d_dayofyear);                // how many days left in year
?>
Stephen
08-Jan-2007 10:43
There are several warnings here about using mktime() to determine a date difference because of daylight savings time. However, nobody seems to have mentioned the other obvious problem, which is leap years.

Leap years mean that any effort to use mktime() and time() to determine the age (positive or negative) of some timestamp in years will be flawed. There are some years that are 366 days long, therefore you cannot say that there is a set number of seconds per year.

Timestamps are good for determining *real* time, which is not the same thing as *human calendar* time. The Gregorian calendar is only an approximation of real time, which is tweaked with daylight savings time and leap years to make it conform more to humans' expectations of how time should or ought to work. Timestamps are not tweaked and therefore are the only authoritative way of recording in computers a proper order of succession of events, but they cannot be integrated with a Gregorian system unless you take both leap years and DST into account. Otherwise, you may get the wrong number of years when you are approaching a value of exactly X years.

As for PHP, you could still use timestamps as a way of determining age if you took into account not only DST but also whether or not each year is a leap year and adjusted your calculations accordingly. However, this could become messy and inefficient.

There is an alternative approach to calculating days given the day, month and year of the dates to be compared. Compare the years first, and then compare the month and day - if the month and day have already passed (or, if you like, if they match the current month and day), then add 1 to the total for the years.

This solution works because it stays within the Gregorian system and doesn't venture into the world of timestamps.

Here is a good discussion of this issue:

http://forums.devshed.com/php-development-5/
need-to-get-the-age-between-dob-
and-today-29925.html?&highlight=age+leap

[the above link was too long; combine the three lines to get the URL]

There is also the issue of leap seconds, but this will only arise if you literally need to get the *exact* age in seconds. In that case, of course, you would also need to verify that your timestamps are exactly correct and are not delayed by script processing time, plus you would need to determine whether your system conforms to UTC, etc. I expect this will hardly be an issue for anybody using PHP, however if you are interested there is an article on this issue on Wikipedia:

http://en.wikipedia.org/wiki/Leap_second
jsebfranck
07-Nov-2006 12:42
There are several notes for mktime which use the number 86400 to differentiate two days. However this technique may pose a problem in case there is a day where the hour change between the two dates to compare.

Consequently, if you want the timestamp difference between the day where the hour change and the next day, it will not be equals to 86400 but either 82800 in case its the winter change of hour day or 90000 for the summer change of hour day.

For example in 2006 :

<?php
echo mktime(0,0,0,10,29,2006) - mktime(0,0,0,10,30,2006); // -90 000
?>
scratch_fury at yahoo dot com
24-Aug-2006 05:07
In response to the post by "nicky" on July 9, 2006:

Just so everyone's clear, if you have a date string formatted in a standard way, you'll probably want to go ahead and use PHP's built-in strtotime() function.  The advantage to using nicky's str2time() function seems to be that you can specify how the date string you're passing in is formatted, so you can deal with non-standard date strings.
carlo dot tafuro at poste dot it
08-May-2006 11:40
Negative timestamps give problem also using linux as guest operating system inside WMvare with Windows host operating system.
colin dot horne at gmail dot com
31-Mar-2005 06: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

// January 1, 2005
print date ("F j, Y", mktime (0,0,0,13,1,2004));

// December 1, 2003
print date ("F j, Y", mktime (0,0,0,0,1,2004));

// February 1, 2005
print date ("F j, Y", mktime (0,0,0,14,1,2004));

// November 1, 2003
print date ("F j, Y", mktime (0,0,0,-1,1,2004));

?>
Romain Sam
25-Mar-2005 03:50
Under Windows, mktime goes until 2038-01-19 (03:14:07 ...)
joakim stai
28-Mar-2004 06: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"));
praas at NOSPAM dot ision dot nl
01-Feb-2004 08: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")));
iain at seatofthepants dot net
09-Dec-2003 03: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.
trahma
20-Nov-2003 08: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 04: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:

<?php
print(date("d/m/Y H:i:s",mktime(0,0,0,3,(27 + 1),2004)));
?>
OUTPUT "28/03/2004 02:00:00"

<?php
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

strftime> <microtime
Last updated: Fri, 03 Jul 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites