DateTime::format

DateTimeImmutable::format

DateTimeInterface::format

date_format

(PHP 5 >= 5.2.1, PHP 7, PHP 8)

DateTime::format -- DateTimeImmutable::format -- DateTimeInterface::format -- date_formatRetourne une date formatée suivant le format fourni

Description

Style orienté objet

public DateTime::format(string $format): string
public DateTimeImmutable::format(string $format): string
public DateTimeInterface::format(string $format): string

Style procédural

date_format(DateTimeInterface $object, string $format): string

Retourne une date formatée suivant le format fourni.

Liste de paramètres

object

Seulement en style procédural : un objet DateTime retourné par date_create()

format

Le format de la date désirée. Voir les options de formatage ci-dessous. Il existe aussi de nombreuses constantes de dates qui peuvent être utilisées, ce qui fait que DATE_RSS va remplacer le format "D, d M Y H:i:s".

Les caractères suivants sont reconnus dans le paramètre format
Caractères pour le paramètre format Description Exemple de valeurs retournées
Jour --- ---
d Jour du mois, sur deux chiffres (avec un zéro initial) 01 à 31
D Jour de la semaine, en trois lettres (et en anglais - par défaut : en anglais, ou sinon, dans la langue locale du serveur) Mon à Sun
j Jour du mois sans les zéros initiaux 1 à 31
l ('L' minuscule) Jour de la semaine, textuel, version longue, en anglais Sunday à Saturday
N Représentation numérique ISO-8601 du jour de la semaine 1 (pour Lundi) à 7 (pour Dimanche)
S Suffixe ordinal d'un nombre pour le jour du mois, en anglais, sur deux lettres st, nd, rd ou th. Fonctionne bien avec j
w Jour de la semaine au format numérique 0 (pour dimanche) à 6 (pour samedi)
z Jour de l'année 0 à 365
Semaine --- ---
W Numéro de semaine dans l'année ISO-8601, les semaines commencent le lundi Exemple : 42 (la 42ème semaine de l'année)
Mois --- ---
F Mois, textuel, version longue; en anglais, comme January ou December January à December
m Mois au format numérique, avec zéros initiaux 01 à 12
M Mois, en trois lettres, en anglais Jan à Dec
n Mois sans les zéros initiaux 1 à 12
t Nombre de jours dans le mois 28 à 31
Année --- ---
L Est ce que l'année est bissextile 1 si bissextile, 0 sinon.
o La numérotation de semaine dans l'année ISO-8601. C'est la même valeur que Y, excepté si le numéro de la semaine ISO (W) appartient à l'année précédente ou suivante, cette année sera utilisée à la place. Exemples : 1999 ou 2003
Y Année sur 4 chiffres Exemples : 1999 ou 2003
y Année sur 2 chiffres Exemples : 99 ou 03
Heure --- ---
a Ante meridiem et Post meridiem en minuscules am ou pm
A Ante meridiem et Post meridiem en majuscules AM ou PM
B Heure Internet Swatch 000 à 999
g Heure, au format 12h, sans les zéros initiaux 1 à 12
G Heure, au format 24h, sans les zéros initiaux 0 à 23
h Heure, au format 12h, avec les zéros initiaux 01 à 12
H Heure, au format 24h, avec les zéros initiaux 00 à 23
i Minutes avec les zéros initiaux 00 à 59
s Secondes avec zéros initiaux 00 à 59
u Microsecondes. Notez que la fonction date() génèrera toujours 000000 vu qu'elle prend un paramètre de type entier, alors que la méthode DateTime::format() supporte les microsecondes si DateTime a été créée avec des microsecondes. Exemple : 654321
v Millisecondes. Même note que pour u. Exemple: 654
Fuseau horaire --- ---
e L'identifiant du fuseau horaire Exemples : UTC, GMT, Atlantic/Azores
I (i majuscule) L'heure d'été est activée ou pas 1 si oui, 0 sinon.
O Différence d'heures avec l'heure de Greenwich (GMT), sans deux-points entre les heures et les minutes Exemple : +0200
P Différence avec l'heure Greenwich (GMT) avec un deux-points entre les heures et les minutes Exemple : +02:00
p Identique à P, mais retourne Z au lieu de +00:00 Exemple : +02:00
T Abréviation du fuseau horaire Exemples : EST, MDT ...
Z Décalage horaire en secondes. Le décalage des zones à l'ouest de la zone UTC est négatif, et à l'est, il est positif. -43200 à 50400
Date et Heure complète --- ---
c Date au format ISO 8601 2004-02-12T15:19:21+00:00
r Format de date » RFC 2822 Exemple : Thu, 21 Dec 2000 16:01:070200
U Secondes depuis l'époque Unix (1er Janvier 1970, 0h00 00s GMT) Voir aussi time()

Les caractères non reconnus seront imprimés tels quels. "Z" retournera toujours 0 lorsqu'il est utilisé avec gmdate().

Note:

Sachant que cette fonction n'accepte que des entiers sous la forme de timestamp, le caractère u n'est utile que lors de l'utilisation de la fonction date_format() avec un timestamp utilisateur créé avec la fonction date_create().

Valeurs de retour

Retourne la date formatée, sous forme de chaîne de caractères, en cas de succès.

Historique

Version Description
8.0.0 Antérieur à cette version, false était retourné en cas d'échec.
8.0.0 Le caractère de format p a été ajouté.

Exemples

Exemple #1 Exemple avec DateTime::format()

Style orienté objet

<?php
$date 
= new DateTime('2000-01-01');
echo 
$date->format('Y-m-d H:i:s');
?>

Style procédural

<?php
$date 
date_create('2000-01-01');
echo 
date_format($date'Y-m-d H:i:s');
?>

L'exemple ci-dessus va afficher :

2000-01-01 00:00:00

Notes

Cette méthode n'utilise pas les locales. Tous les affichages seront en anglais.

Voir aussi

  • date() - Formate une date/heure locale
add a note add a note

User Contributed Notes 10 notes

up
112
craig dot constable at gmail dot com
12 years ago
Using a datetime field from a mysql database e.g. "2012-03-24 17:45:12"

<?php

$result
= mysql_query("SELECT `datetime` FROM `table`");
$row = mysql_fetch_row($result);
$date = date_create($row[0]);

echo
date_format($date, 'Y-m-d H:i:s');
#output: 2012-03-24 17:45:12

echo date_format($date, 'd/m/Y H:i:s');
#output: 24/03/2012 17:45:12

echo date_format($date, 'd/m/y');
#output: 24/03/12

echo date_format($date, 'g:i A');
#output: 5:45 PM

echo date_format($date, 'G:ia');
#output: 05:45pm

echo date_format($date, 'g:ia \o\n l jS F Y');
#output: 5:45pm on Saturday 24th March 2012

?>
up
6
sparcbr at gmail dot com
3 years ago
To add literal characteres youi can escape with backslash (\):

$date = new DateTime();
echo $date->format('Ymd\Thms');
up
36
soul dot enforcer at gmail dot com
10 years ago
For full reference of the supported format character and results,
see the documentation of date() :
http://www.php.net/manual/en/function.date.php
up
34
daysnine at gmail dot com
10 years ago
Seems like datetime::format does not really support microseconds as the documentation under date suggest it will.

Here is some code to generate a datetime with microseconds and timezone:

private function udate($format = 'u', $utimestamp = null) {
        if (is_null($utimestamp))
            $utimestamp = microtime(true);

        $timestamp = floor($utimestamp);
        $milliseconds = round(($utimestamp - $timestamp) * 1000000);

        return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
    }

echo udate('Y-m-d H:i:s.u T');
// Will output something like: 2014-01-01 12:20:24.42342 CET
up
9
mesa dot fx at gmail dot com
5 years ago
There is a bit confusing logic may appear using year week number:

<?php
echo (new \DateTime("2018-12-31 13:05:21"))->format("YW") . PHP_EOL;
?>

will output 201801, not 201901 nor 201852, because of strange ISO_8601-2004 standard: the  first  calendar  week  of  a  year  is  that  one  which  includes  the  first  Thursday  of  that  year, so this date (it is Monday) do belong to the first week of 2019 (this is why 'W' format gives 01), but internal timestamp is of 2018 (and 'Y' format obey this), therefore getting us unexpected result of 201801. So be careful when using this output with something important (i know projects where this was used to form MySQL partitions).
up
-7
ca at agercon dot dk
12 years ago
The date_format can be use to get the last day of February:

<?php

function last_day_of_feb ($year) {
# The 0th day of a month is the same as the last day of the month before
       
$ultimo_feb_str = $year . "-03-00";
       
$ultimo_feb_date = date_create($ultimo_feb_str);
       
$return = date_format($ultimo_feb_date, "Y-m-d");
        return
$return;
}

echo
last_day_of_feb(2011) . "\n"; # 2011-02-28
echo last_day_of_feb(2012) . "\n"; # 2011-02-29

?>
up
-2
tuxedobob
3 years ago
I'm actually not sure whether this is a bug, but here's something that tripped me up on PHP 7.3.

I have a date that looks like this: 'November 3, 2020 11:13 (CST)'

I tried to format it using this format string: 'F j, Y H:i (T)'

That didn't work.

What *did* work was the format string without the parentheses: 'F j, Y H:i T'.

This string also parsed the timezone when the time zone *didn't* have parentheses surrounding it: 'November 3, 2020 11:13 CST'.

It seems as though the T token is a little greedy with surrounding parentheses, so don't include them in your format string.
up
-26
prussell at cloudworksconsulting dot com
9 years ago
The udate function is a great start, but the formatting of the milliseconds is a little off. If it is within the first 100000 microseconds then the string will be less than 6 characters, so 0.012435 will appear as 0.12345. The revision below fixes this.

function udate($strFormat = 'u', $uTimeStamp = null)
{

    // If the time wasn't provided then fill it in
    if (is_null($uTimeStamp))
    {
        $uTimeStamp = microtime(true);
    }

    // Round the time down to the second
    $dtTimeStamp = floor($uTimeStamp);

    // Determine the millisecond value
    $intMilliseconds = round(($uTimeStamp - $dtTimeStamp) * 1000000);
    // Format the milliseconds as a 6 character string
    $strMilliseconds = str_pad($intMilliseconds, 6, '0', STR_PAD_LEFT);

    // Replace the milliseconds in the date format string
    // Then use the date function to process the rest of the string
    return date(preg_replace('`(?<!\\\\)u`', $strMilliseconds, $strFormat), $dtTimeStamp);
}
up
-12
info at ibusweb dot com
5 years ago
$saved_time="2019-03-09 14:25:20";
    $formated_saved_time = new DateTime($saved_time);
    $current_time = new DateTime();
    $interval = $current_time->diff($formated_saved_time);
 
      if (!empty($interval->format('%a'))){
       $time_difference=$interval->format('%a days ago');
        } elseif ($formated_saved_time->format('d') != $current_time->format('d')){
             $time_difference="yesterday";
             }elseif (!empty($interval->format('%h'))){
                     $time_difference=$interval->format('%h hr, %i min ago');
                     } elseif (!empty($interval->format('%i'))){
                              $time_difference=$interval->format('%i min ago');
                              } elseif (!empty($interval->format('%s'))){
                                $time_difference=$interval->format('%s sec ago');
  }

output ----- posted 4 hr, 12 min ago at 2019-03-09 14:25:20

see the code in action here
https://eval.in/1081921
up
-50
chris at codewiz dot biz
10 years ago
I believe this is a bug but its note-worthy if it is intended (I am using PHP 5.5.3).

$ php --version

PHP Warning:  Module 'xdebug' already loaded in Unknown on line 0
PHP 5.5.3-1ubuntu2.1 (cli) (built: Dec 12 2013 04:24:35)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies
    with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans
    with Zend OPcache v7.0.3-dev, Copyright (c) 1999-2013, by Zend Technologies

What is happening:

DateTime()->format() will modify the timezone. So do not expect the public date property to be returned (format mask applied) based on the current public timezone property. format will decide that when calling ->format() it will use the server timezone which eliminates all usefulness of ->setTimezone().

<?php
            $nowUtc
= new \DateTime( 'now',  new \DateTimeZone( 'UTC' ) );
            echo
'$nowUtc'.PHP_EOL;
           
var_dump($nowUtc);
           
$nowUtc = new \DateTime( 'now',  new \DateTimeZone( 'UTC' ) );
            echo
'$nowUtc->format(\'Y-m-d h:i:s\')'.PHP_EOL;
           
var_dump($nowUtc->format('Y-m-d h:i:s'));
           
$nowUtc->setTimezone( new \DateTimeZone( 'Australia/Sydney' ) );
            echo
'$nowUtc->setTimezone( new \DateTimeZone( \'Australia/Sydney\' ) )'.PHP_EOL;
           
var_dump($nowUtc);
            echo
'$nowUtc->format(\'Y-m-d h:i:s\')'.PHP_EOL;
           
var_dump($nowUtc->format('Y-m-d h:i:s'));exit;
?>

outputs;

$nowUtc

object(DateTime)[2607]
  public 'date' => string '2014-02-13 02:42:48' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'UTC' (length=3)

$nowUtc->format('Y-m-d h:i:s')

string '2014-02-13 02:42:48' (length=19)

$nowUtc->setTimezone( new \DateTimeZone( 'Australia/Sydney' ) )

object(DateTime)[2608]
  public 'date' => string '2014-02-13 13:42:48' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Australia/Sydney' (length=16)

$nowUtc->format('Y-m-d h:i:s')

string '2014-02-13 01:42:48' (length=19) // expected 2014-02-13 13:42:48 based on Australia/Sydney - what is 2014-02-13 01:42:48 from anyway!
To Top