Articles

The month of PHP functions : easy dating

  • Ecrit par Rodolphe Eveilleau
Image pour le titre du contenu

Ce document est aussi disponible en français fr 


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

Commentaires

Vous pouvez ajouter votre commentaire!


Vous devez vous connecter pour commenter