You are on page 1of 11

Downloads

Documentation
Get Involved
Help

Search

Getting Started
Introduction
A simple tutorial
Language Reference
Basic syntax
Types
Variables
Constants
Expressions
Operators
Control Structures
Functions
Classes and Objects
Namespaces
Enumerations
Errors
Exceptions
Fibers
Generators
Attributes
References Explained
Predefined Variables
Predefined Exceptions
Predefined Interfaces and Classes
Context options and parameters
Supported Protocols and Wrappers

Security
Introduction
General considerations
Installed as CGI binary
Installed as an Apache module
Session Security
Filesystem Security
Database Security
Error Reporting
User Submitted Data
Hiding PHP
Keeping Current
Features
HTTP authentication with PHP
Cookies
Sessions
Dealing with XForms
Handling file uploads
Using remote files
Connection handling
Persistent Database Connections
Command line usage
Garbage Collection
DTrace Dynamic Tracing

Function Reference
Affecting PHP's Behaviour
Audio Formats Manipulation
Authentication Services
Command Line Specific Extensions
Compression and Archive Extensions
Cryptography Extensions
Database Extensions
Date and Time Related Extensions
File System Related Extensions
Human Language and Character Encoding Support
Image Processing and Generation
Mail Related Extensions
Mathematical Extensions
Non-Text MIME Output
Process Control Extensions
Other Basic Extensions
Other Services
Search Engine Extensions
Server Specific Extensions
Session Extensions
Text Processing
Variable and Type Related Extensions
Web Services
Windows Only Extensions
XML Manipulation
GUI Extensions

Keyboard Shortcuts
?
This help
j
Next menu item
k
Previous menu item
gp
Previous man page
gn
Next man page
G
Scroll to bottom
gg
Scroll to top
gh
Goto homepage
gs
Goto search

(current page)
/
Focus search box

DateTime::getOffset »
« DateTime::diff

PHP Manual
Function Reference
Date and Time Related Extensions
Date/Time
DateTimeInterface

Change language:
English
Submit a Pull Request
Report a Bug

DateTime::format
DateTimeImmutable::format
DateTimeInterface::format
date_format
(PHP 5 >= 5.2.1, PHP 7, PHP 8)

DateTime::format -- DateTimeImmutable::format -- DateTimeInterface::format -- date_format — Returns date


formatted according to given format

Description ¶

Object-oriented style

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


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

Procedural style

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

Returns date formatted according to given format.

Parameters ¶

object

Procedural style only: A DateTime object


returned by date_create()
format

The format of the outputted date string. See the formatting


options below. There are also several
predefined date constants
that may be used instead, so for example DATE_RSS
contains the format string 'D,
d M Y H:i:s'.

The following characters are recognized in the


format parameter string
format Example returned
Description
character values
Day --- ---
d Day of the month, 2 digits with leading zeros 01 to 31
D A textual representation of a day, three letters Mon through Sun
j Day of the month without leading zeros 1 to 31
l
Sunday through
(lowercase A full textual representation of the day of the week
Saturday
'L')
1 (for Monday)
N ISO 8601 numeric representation of the day of the week through 7 (for
Sunday)
st, nd, rd or
th.
S English ordinal suffix for the day of the month, 2 characters
Works well with j
0 (for Sunday)
w Numeric representation of the day of the week through 6 (for
Saturday)
z The day of the year (starting from 0) 0 through 365
Week --- ---
Example: 42 (the
W ISO 8601 week number of year, weeks starting on Monday 42nd week in the
year)
Month --- ---
January through
F A full textual representation of a month, such as January or March
December
m Numeric representation of a month, with leading zeros 01 through 12
M A short textual representation of a month, three letters Jan through Dec
n Numeric representation of a month, without leading zeros 1 through 12
t Number of days in the given month 28 through 31
Year --- ---
1 if it is a leap year,
L Whether it's a leap year
0 otherwise.
ISO 8601 week-numbering year. This has the same value as
Y, except
Examples: 1999 or
o that if the ISO week number
(W) belongs to the previous or next year, that
2003
year
is used instead.
A full numeric representation of a year, at least 4 digits,
with - for years Examples: -0055,
Y
BCE. 0787,
1999, 2003
y A two digit representation of a year Examples: 99 or 03
Time --- ---
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
format Example returned
Description
character values
B Swatch Internet time 000 through 999
g 12-hour format of an hour without leading zeros 1 through 12
G 24-hour format of an hour without leading zeros 0 through 23
h 12-hour format of an hour with leading zeros 01 through 12
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
s Seconds with leading zeros 00 through 59
Microseconds. Note that
date() will always generate
000000 since it takes
u an int
parameter, whereas DateTime::format() does
support Example: 654321
microseconds if DateTime was
created with microseconds.
v Milliseconds. Same note applies as for
u. Example: 654
Timezone --- ---
Examples: UTC, GMT,
e Timezone identifier
Atlantic/Azores
1 if Daylight
I (capital
Whether or not the date is in daylight saving time Saving Time, 0
i)
otherwise.
Difference to Greenwich time (GMT) without colon between hours and
O Example: +0200
minutes
Difference to Greenwich time (GMT) with colon between hours and
P Example: +02:00
minutes
p The same as P, but returns Z instead of +00:00
(available as of PHP 8.0.0) Example: +02:00
Examples: EST, MDT,
T Timezone abbreviation, if known; otherwise the GMT offset.
+05
Timezone offset in seconds. The offset for timezones west of UTC is -43200 through
Z
always
negative, and for those east of UTC is always positive. 50400
Full
--- ---
Date/Time
2004-02-
c ISO 8601 date
12T15:19:21+00:00
Example: Thu, 21
r » RFC 2822 formatted date Dec 2000 16:01:07
+0200
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) See also time()

Unrecognized characters in the format string will be printed


as-is. The Z format will always return
0 when
using gmdate().

Note:

Since this function only accepts int timestamps the


u format character is only useful when
using the
date_format() function with user based timestamps
created with date_create().

Return Values ¶
Returns the formatted date string on success.
Changelog ¶

Version Description
8.0.0 Prior to this version, false was returned on failure.
8.0.0 The format character p has been added.

Examples ¶

Example #1 DateTime::format() example

Object-oriented style

<?php

$date = new DateTime('2000-01-01');

echo $date->format('Y-m-d H:i:s');

?>

Procedural style

<?php

$date = date_create('2000-01-01');

echo date_format($date, 'Y-m-d H:i:s');

?>

The above example will output:

2000-01-01 00:00:00

Notes ¶

This method does not use locales. All output is in English.

See Also ¶

date() - Format a local time/date

add a note

User Contributed Notes 10 notes


up
down
114
craig dot constable at gmail dot com ¶
10 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
down
35
soul dot enforcer at gmail dot com ¶
8 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
down
15
sparcbr at gmail dot com ¶
1 year ago
To add literal characteres youi can escape with backslash (\):

$date = new DateTime();

echo $date->format('Ymd\Thms');
up
down
15
mesa dot fx at gmail dot com ¶
3 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
down
33
daysnine at gmail dot com ¶
8 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
down
-4
tuxedobob ¶
1 year 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
down
-15
ca at agercon dot dk ¶
10 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
down
-32
prussell at cloudworksconsulting dot com ¶
7 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
down
-19
info at ibusweb dot com ¶
3 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
down
-55
chris at codewiz dot biz ¶
8 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!
add a note

DateTimeInterface
diff
format
getOffset
getTimestamp
getTimezone
_​_​wakeup

Copyright © 2001-2022 The PHP Group


My PHP.net
Contact
Other PHP.net sites
Privacy policy
View Source

You might also like