PHP Velho Oeste 2024

DateTimeInterface::format

DateTimeImmutable::format

DateTime::format

date_format

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

DateTimeInterface::format -- DateTimeImmutable::format -- DateTime::format -- date_format按照指定格式返回格式化后的日期

说明

面向对象风格

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

过程化风格

按照指定格式返回格式化后的日期。

参数

object

仅为过程化风格:由 date_create() 返回的 DateTime 类型的对象。

format

输出的日期 string 的格式。参见下面的格式化选项。也有几个预定义日期常量可以代替。例如 DATE_RSS 包含格式化字符串 'D, d M Y H:i:s'

format 参数字符串可以识别以下字符
format 字符 说明 返回值示例
--- ---
d 月份中的第几天,有补零的两位数字 0131
D 文字表示星期几,三个字母 MonSun
j 月份中的第几天,没有补零 131
l(小写 'L') 完整文本表示星期几 SundaySaturday
N ISO 8601 数字表示星期几 1(星期一)到 7(星期天)
S 月份中的第几天英文后缀,两个字符 stndrdth。可以和 j 一起使用
w 数字表示星期几 0(星期天)到 6(星期六)
z 一年中的第几天(从 0 开始) 0365
--- ---
W ISO 8601 格式当年中的第几周,每周从周一开始 示例:42(当年的第 42 周)
--- ---
F 月份的完整文本表示,比如 January 或者 March JanuaryDecember
m 月份的数字表示,补零 0112
M 简短文本表示月份,三个字母 JanDec
n 数字表示几月份,不补零 112
t 指定月份的天数 2831
--- ---
L 是否是闰年 如果是闰年为 1,否则为 0
o ISO 8601 数字年份表示。这和 Y 值相同,但如果 ISO 周数(W)属于上一年或者下一年,则用那一年。 示例:19992003
X 年份的展开全数字表示,至少四位,- 表示公元前,+ 表示公元。 示例:-0055+0787+1999+10191
x 如果需要,年份可以展开全数字表示,如果可能的话,也可以用标准的全数字(Y)表示。至少有四位数字。公元前以 - 为前缀,年份不小于 10000 时以 + 为前缀。 示例:-0055, 0787, 1999, +10191
Y 年份完整数字表示,至少四位,使用 - 表示公元前。 示例:-005507871999200310191
y 两位数的年份表示 示例:9903
时间 --- ---
a 小写的上午和下午 ampm
A 大写的上午和下午 AMPM
B Swatch 互联网时间 000999
g 不补零的小时(12 小时制) 112
G 不补零的小时(24 小时制) 023
h 补零的小时(12 小时制) 0112
H 补零的小时(24 小时制) 0023
i 补零的分钟 0059
s 补零的秒 0059
u 微秒。注意 date() 总是生成 000000,因为它需要一个 int 参数,而如果 DateTime 是使用微秒创建的,则 DateTime::format() 支持微秒。 示例:654321
v 毫秒。与 u 的说明相同。 示例:654
时区 --- ---
e 时区标识符 示例:UTCGMTAtlantic/Azores
I(大写 i) 是否为夏令时 如果是夏令时为 1,否则为 0
O 跟格林尼治时间(GMT)的差异,小时和分钟时间没有冒号 示例:+0200
P 跟格林尼治时间(GMT)的差异,小时和分钟时间有冒号 示例:+02:00
p P 相同,区别是使用 Z 替换 +00:00 返回(PHP 8.0.0 起可用) 示例:Z+02:00
T 如果知道会返回时区缩写,否则返回 GMT 时差。 示例:ESTMDT+05
Z 以秒为单位的时差。UTC 以西的时区为负的时差,以东为正的时差。 -4320050400
完整日期/时间 --- ---
c ISO 8601 日期 2004-02-12T15:19:21+00:00
r » RFC 2822/» RFC 5322 格式化时间 示例:Thu, 21 Dec 2000 16:01:07 +0200
U 从 Unix 纪元(January 1 1970 00:00:00 GMT)到至今的秒数 参见 time()

格式字符串中无法识别的字符将会原样打印。当使用 gmdate() 时,Z 格式将始终返回 0

注意:

由于本函数仅接受 int 类型时间戳,所以 u 格式化标识符仅在用户使用 date_create() 且使用 date_format() 创建时间戳时才有用。

返回值

成功时返回格式化后的日期字符串。

更新日志

版本 说明
8.2.0 新增 Xx 格式化字符。
8.0.0 新增 p 格式化字符。

示例

示例 #1 DateTimeInterface::format() 示例

面向对象风格

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

过程化风格

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

以上示例会输出:

2000-01-01 00:00:00

示例 #2 更多示例

<?php
// 设置使用的默认时区。
date_default_timezone_set('UTC');

// 现在
$date = new DateTimeImmutable();

// 打印类似:Wednesday
echo $date->format('l'), "\n";

// 打印类似:Wednesday 19th of October 2022 08:40:48 AM
echo $date->format('l jS \o\f F Y h:i:s A'), "\n";

/* 在 format 参数中使用常量 */
// 打印类似:Wed, 19 Oct 2022 08:40:48 +0000
echo $date->format(DateTimeInterface::RFC2822), "\n";
?>

通过对格式化字符串中的识别字符添加反斜线,对其转义来防止被解析。如果带有反斜线的字符已经是特殊序列,那么还要对反斜线进行转义。

示例 #3 格式化时转义字符

<?php
$date
= new DateTimeImmutable();

// 打印类似:Wednesday the 19th
echo $date->format('l \t\h\e jS');
?>

要格式化其它语言的日期,可以使用 IntlDateFormatter::format() 代替 DateTimeInterface::format()

注释

此方法不使用区域设置,所有的输出都是英文。

参见

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
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
15
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
14
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
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
-4
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
-15
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
-32
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
-19
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
-55
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