Articles
Ce document est aussi disponible en français
The most used function to generate dates is certainly mktime(). Though, it is not the most convenient, to use : one has to know the long list of arguments, and never mistake months and days...
A highly convenient function for generating timestamps is strtotime(). The main goal of this function is to turn English langage in a timestamp.
Example n°1 :
<?php echo strtotime('2007-04-18'); /** * Result : 1176847200 */ ?>
L'un des intérêts de cette fonction est de pouvoir créer des dates futures ou passées très simplement. Pour cela il vous suffit de respecter quelques standards.
Exemple n°2 :
<?php /** * Today, 2007-04-16 */ echo date('Y-m-d', strtotime('-1 month +5 days')); /** * Result : 2007-03-23 */ ?>
La fonction strtotime() accept also a second parameter : a timestamp. This will be the reference date for the relative calculations. For example, if you want to know what day of the week will be the next valentine's day, you may use this :
Example n°3 :
<?php /** * Setting the application in French */ setlocale(LC_ALL, 'fr_FR', 'fra'); echo strftime('%A', strtotime('+1 year', strtotime('14 february'))); /** * Result : jeudi (thursday) */ echo strftime('%Y', strtotime('today'); /** * Result : 2007 */ echo strftime('%A', strtotime('next monday'); /** * Result : lundi, of course! */ ?>
strftime() supports locale, and allow the conversion of the date in a locale language.
Keep in mind
- Available since PHP 4.
- Works only in English.
- strtotime() returns false if the date couldn't be understood.
- The available date formats are the one described here : http://www.gnu.org/software/tar/manual/html_node/tar_109.html. PHP version will support some of them, and also add it own specific format in the mix.
- It is recommanded to set the time zone before using those functinos. See http://fr.php.net/manual/fr/function.date-default-timezone-set.php
Commentaires
Vous pouvez ajouter votre commentaire! |
Vous devez vous connecter pour commenter


