Classe datetime étendue php 5.2

Description

PHP 5.2 a introduit une classe DateTime très pratique. Cette classe étend l'objet DateTime natif d ePHP avec des fonctions de conversion entre formats de date (Objet vers SQL, SQL vers Objet), de calcul entre dates, de gestion des Time Zones, etc.

L'objectif principal ets de démontrer les mécanismes d'extension des classes natives PHP et de créer des onjets Toolbox génériques.

Source / Exemple :


<?php

class labDateTimeException extends Exception
{
} // class labDateTimeException

/**

  • labDateTime Class is a pure object DateTime management class.
  • It is adapted from Qt QDate, QTime and QDateTime classes, with some
  • enhancements
*
  • @package Enfin
  • @subpackage DateTime
  • @copyright Copyright (c) 2001-2009 LAB Project
  • @author JC Richard <jcrichard@lab-project.net>
  • @version 2.0.0
  • /
class labDateTime extends DateTime { const TextDate = 0 ; const ISODate = 1 ; const LocaleDate = 2 ; /**
  • Builds a new labDateTime object
*
  • @param integer Needed year
  • @param integer Needed month
  • @param integer Needed day
  • @param integer Needed hour
  • @param integer Needed minute
  • @param integer Needed second
*
  • @note all parameters are optional and default to default date/time
*
  • @throws <b>labDateTimeException</b> if date is invalid
  • /
public function __construct( $year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null ) { parent::__construct() ; if ( $year === null ) $year = (int)date( 'Y' ) ; if ( $month === null ) $month = (int)date( 'm' ) ; if ( $day === null ) $day = (int)date( 'd' ) ; if ( $hour === null ) $hour = (int)date( 'G' ) ; if ( $minute === null ) $minute = (int)date( 'i' ) ; if ( $second === null ) $second = (int)date( 's' ) ; if ( self::isValid( $year, $month, $day ) ) { $this->setDate( $year, $month, $day ) ; $this->setTime( $hour, $minute, $second ) ; } else { throw new labDateTimeException( 'Invalid date: %s', "$year-$month-$day" ) ; } } // __construct /**
  • Wrapper to PHP date_default_timezone_set function
*
  • @param string a valid timezone name
*
  • @return bool True on success
  • /
static public function setDefaultTimeZone( $tz = 'UTC' ) { return date_default_timezone_set( $tz ) ; } // setTimeZone /**
  • Creates an labDateTime object from SQL Date
*
  • @param string SQL Date
*
  • @return labDateTime object
  • /
static public function createFromSQL( $dt ) { return new labDateTime( substr( $dt, 8, 2 ), substr( $dt, 5, 2 ), substr( $dt, 0, 4 ) ) ; } // createFromSQL /**
  • Checks if a date is valid
*
  • @param integer Year
  • @param integer Month
  • @param integer Day
*
  • @return bool True if date is valid
  • /
static public function isValid( $y = null, $m = null, $d = null ) { if ( $y === null || $m === null || $d === null ) return false ; return checkdate( $m, $d, $y ) ; } // isValid /**
  • Returns Year
*
  • @return integer Year
  • /
public function year() { return (int)$this->format( 'Y' ) ; } // year /**
  • Returns Month
*
  • @return integer Month
  • /
public function month() { return (int)$this->format( 'n' ) ; } // month /**
  • Returns Day
*
  • @return integer Day
  • /
public function day() { return (int)$this->format( 'd' ) ; } // day /**
  • Returns Hour
*
  • @return integer Hour
  • /
public function hour() { return (int)$this->format( 'G') ; } // hour /**
  • Returns Minute
*
  • @return integer Minute
  • /
public function minute() { return (int)$this->format( 'i') ; } // minute /**
  • Returns Second
*
  • @return integer Second
  • /
public function second() { return (int)$this->format( 's') ; } // second /**
  • Returns Day Of Week
*
  • @param bool True for European Monday First
*
  • @return integer Day Number in Week 1...7 or 0...6
  • /
public function dayOfWeek( $mondayFirst = true ) { return (int)$this->format( $mondayFirst ? 'N' : 'x' ) ; } // dayOfWeek /**
  • Returns Day in Year
*
  • @return integer Day in Year
*
  • @note This differs from PHP statement. We return days in range 1...366 as in Qt
  • /
public function dayOfYear() { return (int)$this->format( 'z' ) +1 ; } // dayOfYear /**
  • Returns the number of days in month
*
  • @return integer 28 to 31
  • /
public function daysInMonth() { return $this->format( 't' ) ; } // daysInMonth /**
  • Returns week number
*
  • @returns current week number for date, ISO-8601 conformant
  • /
public function weekNumber() { return $this->format( 'W' ) ; } // weekNumber /**
  • Returns the number of days between 2 dates
*
  • @param object a labDateTime object
*
  • @return integer the number of days between the dates
  • /
public function daysTo( labDateTime $dt ) { $me = mktime( 0, 0,0, $this->month(), $this->day(), $this->year() ) ; $you = mktime( 0, 0,0, $dt->month(), $dt->day(), $dt->year() ) ; $negate = $you < $me ; $val = (int)( ( $negate ? $me - $you : $you - $me ) / 86400 ) ; return $negate ? (int)"-$val" : $val ; } // daysTo /**
  • Returns the time between 2 dates
*
  • @param object a labDateTime object
*
  • @return integer the number of seconds between events
  • /
public function timeTo( labDateTime $dt ) { $me = mktime( $this->hour, $this->minute, $this->second, $this->month(), $this->day(), $this->year() ) ; $you = mktime( $dt->hour, $dt->minute, $dt->second, $dt->month(), $dt->day(), $dt->year() ) ; $negate = $you < $me ; $val = ( $negate ? $me - $you : $you - $me ) ; return $negate ? (int)"-$val" : $val ; } // timeTo /**
  • Returns the number of days in year
*
  • @returns integer 365 or 366
  • /
public function daysInYear() { return (bool)$this->format( 'L' ) ? 366 : 365 ; } // daysInYear /**
  • Returns date formated as SQLDate format
*
  • @return string SQL Formated date
  • /
public function SQLDate() { return $this->format( 'Y-m-d' ) ; } // SQLDate /**
  • Returns date formated as SQLDateTime format
*
  • @return string SQL Formated dateTime
  • /
public function SQLDateTime() { return $this->format( 'Y-m-d H:i:s' ) ; } // SQLDateTime /**
  • Returns a human readable string representation of date
*
  • This method can get a constant representation for format or a valid format string
  • constants are those defined in this class: TextDate, LocaleDate or ISODate
*
  • @param mixed the format constant or string
  • @param bool true if time must be added
*
  • @return string formated date
  • /
public function toString( $format = self::LocaleDate, $withtime = true ) { if ( $format == self::TextDate ) { return $withtime ? $this->format( 'Y-m-d G:i:s' ) : $this->format( 'Y-m-d' ); } elseif ( $format == self::ISODate ) { return $this->format( 'c' ) ; } elseif ( $format == self::LocaleDate ) { $format = $withtime ? '%A %d %B %Y, %T' : '%A %d %B %Y' ; } return strftime( $format, mktime( 0, 0,0, $this->month(), $this->day(), $this->year() ) ) ; } // toString /**
  • Add Any value to a date and returns the new object
*
  • @param integer value to add
  • @param string a valid string such as day, days, year, minute...
*
  • @return object a labDateTime instance with the new values.
  • /
private function addAny( $w, $txt ) { if ( (int)$w == 0 ) return false ; if ( $w > 0 ) { $w = "+$w $txt" ; } else { $w = "$w $txt" ; } $ret = clone $this ; $ret->modify( $w ) ; return $ret ; } // addAny /**
  • Adds or substracts days to a date
*
  • @param integer value to add ie 10 or -5
*
  • @return object an instance of labDateTime with new value
  • /
public function addDays( $ndays ) { return $this->addAny( $ndays, 'days' ) ; } // addDays /**
  • Adds or substracts months to a date
*
  • @param integer value to add ie 10 or -5
*
  • @return object an instance of labDateTime with new value
  • /
public function addMonths( $nmonths ) { return $this->addAny( $nmonths, 'months' ) ; } // addMonths /**
  • Adds or substracts years to a date
*
  • @param integer value to add ie 10 or -5
*
  • @return object an instance of labDateTime with new value
  • /
public function addYears( $nyears ) { return $this->addAny( $nyears, 'years' ) ; } // addYears /**
  • Adds or substracts hours to a date
*
  • @param integer value to add ie 10 or -5
*
  • @return object an instance of labDateTime with new value
  • /
public function addHours( $nhours ) { return $this->addAny( $nhours, 'hours' ) ; } // addHours /**
  • Adds or substracts minutes to a date
*
  • @param integer value to add ie 10 or -5
*
  • @return object an instance of labDateTime with new value
  • /
public function addMinutes( $nmins ) { return $this->addAny( $nmins, 'minutes' ) ; } // addMinutes /**
  • Adds or substracts seconds to a date
*
  • @param integer value to add ie 10 or -5
*
  • @return object an instance of labDateTime with new value
  • /
public function addSeconds( $nsecs ) { return $this->addAny( $nsecs, 'seconds' ) ; } // addSeconds /**
  • Returns a labDateTime instance with current date and time set
*
  • @return object an instance of labDateTime class
  • /
static public function currentDate() { return new labDateTime() ; } // currentDate /**
  • Returns true if year is bissextile
*
  • @param integer Year to check
*
  • @return bool True if year is bisextile
  • /
static public function isBisextile( $year ) { $y = new labDateTime( $year ) ; return (bool)$y->format( 'L' ) ; } // isBisextile /**
  • Returns true if year is bissextile
*
  • @param integer Year to check
*
  • @return bool True if year is bisextile
  • @deprecated Replaced by isBisextile
  • /
static public function isLeapYear( $year ) { return self::isBisextile( $year ) ; } // isLeapYear /**
  • Parses a valid date string and returns an instance of labDateTime
*
  • @param string a valid format string.
*
  • @return object labDateTime instance or false if invalid string
  • /
static public function fromString( $date ) { $a = date_parse( $date ) ; if ( $a['error_count'] > 0 ) { return false ; } return new labDateTime( $a['year'], $a['month'], $a['day'], $a['hour'], $a['minute'], $a['second'] ) ; } // fromString } // class labDateTime

Conclusion :


Sans être exhaustive, l'estension de la classe DateTime en PHP, en suivant la syntaxe classique de Qt (lib en C++) permet de faciliter le portage d'applications Qt, et en pur PHP, d'avoir une classe de manipulation de dates et heures efficace.

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.