Gerer les dates en php avec la class transDater

Avec cette petite class je gère les dates plus facilement. Bien sûr on peut toujours l’améliorer pour lui rajouter la prise en charge de timestamp par exemple, je reste ouvert à vos suggestions.


/**
 * transDater
 *
 * @package
 * @author luc
 * @copyright Copyright (c) 2012
 * @version $Id$
 * @access public
 */
/* la date en entrée doit être valide mais pas de type timestamp */
class TransDater {

    /**
     * TransDater::dateTransform()
     *
     * @param string $dateString
     * @param mixed $newDateFormat
     * @return
     */
    static function dateTransform($dateString = '01-01-1979', $newDateFormat) {
        if ($dateString && ($format = $newDateFormat)) {
            $date = new DateTime($dateString);
            return $date->format($format);
        }
        return (bool) false;
    }

    /**
     * *Si on récupère le numéro du mois de l'année on peut le transformer en nom en toutes lettres
     */
    static function monthTransformFr($date) {
        static $mois = array(
            '01' => 'janvier',
            '02' => 'fevrier',
            '03' => 'mars',
            '04' => 'avril',
            '05' => 'mai',
            '06' => 'juin',
            '07' => 'juillet',
            '08' => 'aout',
            '09' => 'septembre',
            '10' => 'octobre',
            '11' => 'novembre',
            '12' => 'decembre'
        );
        $m           = self::dateTransform($date, 'm');

        if (!empty($mois[$m])) {
            return (string) $mois[$m];
        }
    }

    /**
     * TransDater::dayWord()
     * @abstract Si on récupère le numéro du jour de l'année on peut le transformer en nom en toutes lettres (0->français,1->Anglais,2->Allemand)
     * @param mixed $date
     * @param mixed $int
     * @return
     */
    static function dayWord($date, $int) {
        $french  = array('dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi');
        $english = array('Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Monday');
        $german  = array('Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag', 'Montag');
        switch ($int) {
            case 0 : $day = $french;
                break;
            case 1: $day = $english;
                break;
            case 2: $day = $german;
                break;
            default:
                false;
        } // switch
        $d = self::dateTransform($date, 'w');
        if (!empty($day[$d])) {
            return (string) $day[$d];
        }
        return (bool) false;
    }

    /* fonction : bissextile */

    static function leapYear($date) {
        $date = self::dateTransform($date, 'y-m-d');

        if ((is_int($date / 4) && !is_int($date / 100)) || is_int($date / 400)) {
            return (bool) true;
        } else {
            return (bool) false;
        }
    }

    /**
     * TransDater::datePlusUnMois()
     *
     * @abstract fonction rajoutant un mois a une date
     * @param mixed $date
     * @return string date plus 1 mois
     */
    static function datePlusUnMois($date) {
        $newDate = new DateTime($date);
        $newDate->modify('+1 month');

        return (string) $newDate->format('Y-m-d');
    }

    /**
     * TransDater::dateMoinsUnJour(()
     *
     * @abstract fonction enlevant 1 jour à une date
     * @param mixed $date
     * @return string date moins 1 jour
     */
    static function dateMoinsUnJour($date) {
        $newDate = new DateTime($date);

        return $newDate->modify('-1 day');
    }

    /**
     * TransDater::age()
     *
     * @abstract Fonction pour calculer l'age
     * @param string  date de naissance type 'd/m/Y'
     * @param string  date à laquelle on veux calculer l'age
     * @return age /integer
     */
    static function age($date_naissance, $currentDate = NULL) {
        if ($date_naissance != NULL) {
            if ($currentDate == NULL) {
                $currentDate = date('d/m/Y');
            }
        }
        $arr1 = explode('/', $date_naissance);
        $arr2 = explode('/', $currentDate);
        if (($arr1[1] < $arr2[1]) || (($arr1[1] == $arr2[1]) && ($arr1[0] <= $arr2[0]))) {
            return $arr2[2] - $arr1[2];
        }
        return (int) $arr2[2] - $arr1[2] - 1;
    }

    /**
     * returns the difference, in days, between two dates.  avoids the daylight's savings issue by using GMT
     */
    static function dateDiff($date1, $date2) {
        $date1 = date_parse($date1);
        $date2 = date_parse($date2);
        return ((gmmktime(0, 0, 0, $date1['month'], $date1['day'], $date1['year']) - gmmktime(0, 0, 0, $date2['month'], $date2['day'], $date2['year'])) / 3600 / 24);
    }

    /**
     * @name dateExcelToHuman()
     * @param string $date
     * @return string date
     */
    static function dateExcelToHuman($date) {
        $date = ($date - 25569) * 86400;
        return (string) date('Y-m-d H:i:s', $date);
    }

    /**
     * @abstract Returns elapsed time with human format in french
     *
     * @param     int The timestamp of the date
     * @return    string
     */
    public function elapsed_time($date) {

        $old_time = $date;

        // Current time
        $time = time();

        // Little check
        if ($time < $old_time) {

            return FALSE;
        }

        // Get seconds elapsed
        $seconds = round($time - $old_time);

        // Convert into minutes
        $minutes = round($seconds / 60);

        // Convert into hours
        $hours = round($minutes / 60);

        // Returns
        if ($hours >= 72) {
            return 'Le ' . date('d/m/Y', $old_time);
        } elseif ($hours >= 48 && $hours < 72) {
            return 'Avant Hier';
        } elseif ($hours >= 24 && $hours < 48) {
            return 'Hier';
        } elseif ($hours >= 1) {
            return 'Il y a ' . $hours . ' h';
        } elseif ($minutes >= 1) {
            return 'Il y a ' . $minutes . ' mn';
        } elseif ($seconds == 0) {
            return 'A l\'instant';
        } else {
            return 'Il y a ' . $seconds . ' s';
        }
    }

    static public function addSeconde(\DateTime $date, $seconde) {
        return self::addInterval($date, 'PT' . (int) $seconde . 'S');
    }

    static public function addMonth(\DateTime $date, $month) {
        return self::addInterval($date, 'P' . (int) $month . 'M');
    }

    static public function addDay(\DateTime $date, $day) {
        return self::addInterval($date, 'P' . (int) $day . 'D');
    }

    static public function addYear(\DateTime $date, $year) {
        return self::addInterval($date, 'P' . (int) $year . 'Y');
    }

    static public function addInterval(\DateTime $date, $value) {
        try {
            $interval = new \DateInterval($value);
            $date->add($interval);
        } catch (Exception $exc) {
            throw new \Exception(__METHOD__ . 'The format of $value is not valid (String) exemple : P55S (add 55 second) ');
        }
        return $date;
    }

}

à bientôt Grand maître L


Publié

dans

,

par

Commentaires

Laisser un commentaire

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.