It seems mktime() doesn't return negative timestamps on Linux systems with a version of glibc <= 2.3.3.
mktime
(PHP 4, PHP 5)
mktime — Retourne le timestamp UNIX d'une date
Description
mktime() retourne un timestamp UNIX correspondant aux arguments fournis. Ce timestamp est un entier long, contenant le nombre de secondes entre le début de l'époque UNIX (1er Janvier 1970 00:00:00 GMT) et le temps spécifié.
Les arguments peuvent être omis, de droite à gauche, et tous les arguments manquants sont utilisés avec la valeur courante de l'heure et du jour.
Liste de paramètres
- hour
-
L'heure.
- minute
-
Les minutes
- second
-
Les secondes.
- month
-
Le nombre représentant le mois.
- day
-
Le nombre représentant le jour.
- year
-
L'année, peut être sur deux ou quatre chiffres, avec des valeurs allant de 0 à 69, correspondant au valeur 2000 à 2069 et 70 à 100, correspondant au valeur 1970 à 2000. Sur les systèmes où time_t un entier signé sur 32bits, ce qui est le plus courant de nos jours, la période valide pour year est quelque part près de 1901 et 2038. Cependant, avant PHP 5.1.0, cette intervalle était limitée de 1970 à 2038 sur quelques systèmes (i.e. Windows).
- is_dst
-
Ce paramètre peut être mis à 1 si l'heure d'hiver est appliquée (DST), 0 si elle ne l'est pas, et -1 (par défaut) si on ne sait pas. Si l'on ne sait pas, PHP tente de le traiter lui-même. Ceci peut occasionner des résultats inattendus (mais néanmoins correct). Quelques temps sont invalides si DST est activé sur les systèmes où PHP fonctionne ou is_dist est défini à 1. Si DST est activé e.g. 2:00, tous les temps entre 2:00 et 3:00 sont invalides et la fonction mktime() retourne une valeur indéfinie (généralement une valeur négative). Quelques systèmes (e.g. Solaris 8) activent DST à minuit, donc, le temps 0:30 du jour lorsque DST est activé est évalué à 23:30 du jour précédent.
Note: Depuis PHP 5.1.0, ce paramètre est déprécié. Comme résultat, le nouveau gestionnaire de fuseau horaire doit être utilisé à la place.
Valeurs de retour
mktime() retourne un timestamp Unix des arguments donnés. Si les arguments ne sont pas valides, la fonction retournera FALSE (avant PHP 5.1, elle retournait -1).
Erreurs / Exceptions
Chaque appel à une fonction date/heure générera un message de type E_NOTICE si le fuseau horaire n'est pas valide., et/ou un message de type E_STRICT si vous utilisez la configuration du système ou la variable d'environnement TZ. Voir aussi date_default_timezone_set()
Historique
| Version | Description |
|---|---|
| 3.0.10 | Ajout du paramètre is_dst |
| 5.1.0 | Le paramètre is_dst est déprécié. Fait que la fonction retourne FALSE en cas d'erreur, au lieu de -1. |
| 5.1.0 | Émet un message de type E_STRICT et E_NOTICE lors d'erreurs de fuseaux horaires. |
Exemples
Exemple #1 Exemple avec mktime()
mktime() est pratique pour faire des calculs de dates et des validations, car elle va automatiquement corriger les valeurs invalides. Par exemple, toutes les lignes suivantes vont retourner la même date : "Jan-01-1998".
<?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));
?>
Exemple #2 Dernier jour du mois suivant
Le dernier jour d'un mois peut être décrit comme le jour "0" du mois suivant, et non pas le jour -1. Les deux exemples suivants vont donner : "Le dernier jour de Février 2000 est: 29".
<?php
$lastday = mktime(0, 0, 0, 3, 0, 2000);
echo strftime("Le dernier jour de Fevrier 2000 est : %d", $lastday);
$lastday = mktime(0, 0, 0, 4, -31, 2000);
echo strftime("Le dernier jour de Fevrier 2000 est : %d", $lastday);
?>
Notes
Avant PHP 5.1.0, les valeurs négatives des timestamp ne sont pas supportées sous toutes les versions actuelles de Microsoft Windows. De ce fait, l'intervalle valide pour les années est de 1970 à 2038, inclus.
mktime
13-May-2008 04:34
30-Jan-2008 09: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.)
06-Sep-2007 07: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().
31-Aug-2007 04: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 )
?>
17-Jul-2007 06: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.
11-Jul-2007 03: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.
31-Mar-2007 06: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), 31, 2007 );
$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
?>
08-Jan-2007 11: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
07-Nov-2006 01: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
?>
24-Aug-2006 07: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.
08-May-2006 01:40
Negative timestamps give problem also using linux as guest operating system inside WMvare with Windows host operating system.
31-Mar-2005 08: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));
?>
28-Mar-2004 08: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"));
01-Feb-2004 09: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")));
09-Dec-2003 04: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.
20-Nov-2003 09: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()
18-Nov-2003 05: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
