PHP 5.4.36 Released

DateTime::__construct

date_create

(PHP 5 >= 5.2.0)

DateTime::__construct -- date_createRetourne un nouvel objet DateTime

Description

Style orienté objet

public DateTime::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Style procédural

DateTime date_create ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Retourne un nouvel objet DateTime.

Liste de paramètres

time

Une chaîne date/heure. Les formats valides sont expliqués dans la documentation sur les formats Date et Heure.

Passez NULL ici pour obtenir le temps courant en utilisant le paramètre $timezone.

timezone

Un objet DateTimeZone representant le fuseau horaire de $time.

Si$timezone est omis, le fuseau horaire actuel sera utilisé.

Note:

Le paramètre $timezone et le fuseau horaire actuels sont ignorés lorsque paramètre $time est un timestamp UNIX (e.g. @946684800) ou précise un fuseau (e.g. 2010-01-28T15:00:00+02:00).

Valeurs de retour

Retourne une nouvelle instance DateTime. Style procédural retourne FALSE en cas d'erreur.

Erreurs / Exceptions

Émet un Exception en cas d'erreur.

Historique

Version Description
5.3.0 Si le paramètre time contient un format date/heure invalide, alors une exception sera lancée. Précédemment, une erreur était émise.

Exemples

Exemple #1 Exemple avec DateTime::__construct()

Style orienté objet

<?php
try {
    
$date = new DateTime('2000-01-01');
} catch (
Exception $e) {
    echo 
$e->getMessage();
    exit(
1);
}

echo 
$date->format('Y-m-d');
?>

Style procédural

<?php
$date 
date_create('2000-01-01');
if (!
$date) {
    
$e date_get_last_errors();
    foreach (
$e['errors'] as $error) {
        echo 
"$error\n";
    }
    exit(
1);
}

echo 
date_format($date'Y-m-d');
?>

Les exemples ci-dessus vont afficher :

2000-01-01

Exemple #2 Autres exemples avec DateTime::__construct()

<?php
// date/time spécifiés dans le fuseau de votre machine
$date = new DateTime('2000-01-01');
echo 
$date->format('Y-m-d H:i:sP') . "\n";

// date/time dans un fuseau précis.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo 
$date->format('Y-m-d H:i:sP') . "\n";

// date/time courants dans le fuseau de votre machine
$date = new DateTime();
echo 
$date->format('Y-m-d H:i:sP') . "\n";

// date/time courants dans un fuseau précis.
$date = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo 
$date->format('Y-m-d H:i:sP') . "\n";

// Utilisation d'un timestamp Unix. Notez que le résultat est dans le fuseau UTC.
$date = new DateTime('@946684800');
echo 
$date->format('Y-m-d H:i:sP') . "\n";

// Valeur non existante
$date = new DateTime('2000-02-30');
echo 
$date->format('Y-m-d H:i:sP') . "\n";
?>

L'exemple ci-dessus va afficher quelque chose de similaire à :

2000-01-01 00:00:00-05:00
2000-01-01 00:00:00+12:00
2010-04-24 10:24:16-04:00
2010-04-25 02:24:16+12:00
2000-01-01 00:00:00+00:00
2000-03-01 00:00:00-05:00

Voir aussi

add a note add a note

User Contributed Notes 8 notes

up
13
joel dot kallman at gmail dot com
3 years ago
A definite "gotcha" (while documented) that exists in the __construct is that it ignores your timezone if the $time is a timestamp.  While this may not make sense, the object does provide you with methods to work around it.

<?php
// New Timezone Object
$timezone = new DateTimeZone('America/New_York');

// New DateTime Object
$date =  new DateTime('@1306123200', $timezone);   

// You would expect the date to be 2011-05-23 00:00:00
// But it actually outputs 2011-05-23 04:00:00
echo $date->format('Y-m-d H:i:s');

// You can still set the timezone though like so...       
$date->setTimezone($timezone);

// This will now output 2011-05-23 00:00:00
echo $date->format('Y-m-d H:i:s');
?>
up
10
cHao
3 years ago
There's a reason for ignoring the time zone when you pass a timestamp to __construct.  That is, UNIX timestamps are by definition based on UTC.  @1234567890 represents the same date/time regardless of time zone.  So there's no need for a time zone at all.
up
6
kendsnyder at gmail dot com
4 years ago
The theoretical limits of the date range seem to be "-9999-01-01" through "9999-12-31" (PHP 5.2.9 on Windows Vista 64):

<?php

$d
= new DateTime("9999-12-31");
$d->format("Y-m-d"); // "9999-12-31"

$d = new DateTime("0000-12-31");
$d->format("Y-m-d"); // "0000-12-31"

$d = new DateTime("-9999-12-31");
$d->format("Y-m-d"); // "-9999-12-31"

?>

Dates above 10000 and below -10000 do not throw errors but produce weird results:

<?php

$d
= new DateTime("10019-01-01");
$d->format("Y-m-d"); // "2009-01-01"

$d = new DateTime("10009-01-01");
$d->format("Y-m-d"); // "2009-01-01"

$d = new DateTime("-10019-01-01");
$d->format("Y-m-d"); // "2009-01-01"

?>
up
2
Tim Strehle
4 years ago
"The $timezone parameter and the current timezone are ignored when the $time parameter […] is a UNIX timestamp."

Watch out – this means that these two are NOT equivalent, they result in different timezones (unless your current timezone is GMT):

<?php
$d
= new DateTime(); $d->setTimestamp($t);
echo
$o->format('O');
// +0200

$d = new DateTime('@' . $t);
echo
$o->format('O');
// +0000
?>
up
2
RussellG
1 year ago
Although this function throws an exception on invalid $time values (empty strings, for example), the exception can't be caught because it's a fatal exception. Use functions such as checkdate() and strtotime() to validate the string first. Example #1 should be changed to remove the try/catch block, since it's misleading.
up
1
kendsnyder at gmail dot com
4 years ago
Also forgot to mention, that MySQL "zeroed" dates do not throw an error but produce a non-sensical date:

<?php

$d
= new DateTime("0000-00-00");
$d->format("Y-m-d"); // "-0001-11-30"

?>

Another good reason to write your own class that extends from DateTime.
up
0
rn at alpha9marketing dot com
27 days ago
Note that the DateTime ctor also accepts boolean false and empty strings, and treats them the same as NULL (i.e. result is current date and time). This may lead to unexpected results if you forward function return values without explicitly checking them first.

Empty arrays and boolean true trigger PHP warnings OTOH.

(checked with PHP 5.5.18)
up
0
Dimitar Stoichev
7 months ago
Be careful working with MySQL dates representing point of transition to Daylight Saving Time.
The constructor of DateTime will convert timezone abbreviation to DST but not the time.

<?php

$timeZone
= new DateTimeZone('Europe/Sofia');
           
$transitionToDst = '2014-03-30 03:00:00';

$date = new DateTime($transitionToDst, $timeZone);

// Outputs: Sun Mar 30, 2014 3:00:00 EEST
// Correct: Sun Mar 30, 2014 4:00:00 EEST
echo $date->format('D M j, Y G:i:s T') . '<br>';

// Explicitly setting timezone or adding one second fixes this
$cloneForAdding = clone $date;

$date->setTimezone($timeZone);

// Outputs: Sun Mar 30, 2014 4:00:00 EEST
echo $date->format('D M j, Y G:i:s T') . '<br>';

$cloneForAdding->add(new DateInterval('PT1S'));

// Outputs: Sun Mar 30, 2014 4:00:01 EEST
echo $cloneForAdding->format('D M j, Y G:i:s T');

?>
To Top