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

出力される日付文字列の書式。以下のオプションを参照ください。 定義済みの定数 も用意されており、たとえば DATE_RSS はフォーマット文字列 'D, d M Y H:i:s' と同じ意味になります。

以下の文字が format パラメータ文字列として認識されます
format 文字 説明 戻り値の例
--- ---
d 日。二桁の数字(先頭にゼロがつく場合も) 01 から 31
D 曜日。3文字のテキスト形式。 Mon から Sun
j 日。先頭にゼロをつけない。 1 から 31
l (小文字の 'L') 曜日。フルスペル形式。 Sunday から Saturday
N ISO 8601 形式の、曜日の数値表現 1(月曜日)から 7(日曜日)
S 英語形式の序数を表すサフィックス。2 文字。 st, nd, rd または thjと一緒に使用する ことができる。
w 曜日。数値。 0 (日曜)から 6 (土曜)
z 年間の通算日。数字。(ゼロから開始) 0 から 365
--- ---
W ISO 8601 月曜日に始まる年単位の週番号 例: 42 (年の第 42 週目)
--- ---
F 月。フルスペルの文字。 January から December
m 月。数字。先頭にゼロをつける。 01 から 12
M 月。3 文字形式。 Jan から Dec
n 月。数字。先頭にゼロをつけない。 1 から 12
t 指定した月の日数。 28 から 31
--- ---
L 閏年であるかどうか。 1なら閏年。0なら閏年ではない。
o ISO 8601 形式の週番号による年。これは Y ほぼ同じだが、ISO 週番号 (W)が前年あるいは翌年に属する場合はそちらの年を使うという点が異なる。 例: 1999 あるいは 2003
X 拡張された年の数値表現。少なくとも4桁からなる数値。紀元前の場合は、- が付きます。西暦の場合は + が付きます。 例: -0055, +0787, +1999, +10191
x 必要に応じて拡張された年の数値表現。 拡張する必要がない場合は、通常の年の数値 (Y と同じ)。 少なくとも4桁からなる数値。紀元前の場合は、- が付きます。10000 (10000を含みます) を超える場合は、+ が付きます。 例: -0055, 0787, 1999, +10191
Y 年。少なくとも4桁からなる数値。紀元前の場合は、- が付きます。 例: -0055, 0787, 1999, 2003, 10191
y 年。2 桁の数字。 例: 99 または 03
--- ---
a 午前または午後(小文字) am または pm
A 午前または午後(大文字) AM または PM
B Swatch インターネット時間 000 から 999
g 時。12時間単位。先頭にゼロを付けない。 1 から 12
G 時。24時間単位。先頭にゼロを付けない。 0 から 23
h 時。数字。12 時間単位。 01 から 12
H 時。数字。24 時間単位。 00 から 23
i 分。先頭にゼロをつける。 00 から 59
s 秒。先頭にゼロをつける。 00 から 59
u マイクロ秒。 date() の場合、これは常に 000000 となることに注意しましょう。というのも、 この関数が受け取るパラメータは int 型だからです。 一方 DateTime をマイクロ秒つきで作成した場合は、 DateTime::format() はマイクロ秒にも対応しています。 例: 654321
v ミリ秒。 uと同じ注釈が当てはまります。 例: 654
タイムゾーン --- ---
e タイムゾーン識別子 例: UTC, GMT, Atlantic/Azores
I (大文字の i) サマータイム中か否か 1ならサマータイム中。 0ならそうではない。
O グリニッジ標準時 (GMT) との時差。時間と分の間にコロンは入りません。 例: +0200
P グリニッジ標準時 (GMT) との時差。時間と分をコロンで区切った形式 例: +02:00
p P と同じですが、+00:00 ではなく Z を返します。 (PHP 8.0.0 以降で利用可能) 例: Z または +02:00
T 既知のものについては、タイムゾーンの略称。そうでないものについては、GMT からのオフセット 例: EST, MDT, +05
Z タイムゾーンのオフセット秒数。 UTC の西側のタイムゾーン用のオフセットは常に負です。そして、 UTC の東側のオフセットは常に正です。 -43200 から 50400
全ての日付/時刻 --- ---
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 Epoch (1970 年 1 月 1 日 0 時 0 分 0 秒) からの秒数 time() も参照

フォーマット文字列中の認識されない文字は、そのまま表示されます。 Z 形式は、 gmdate() で使用した場合、常に 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";
/* フォーマット文字で定数を使う */
// Wed, 19 Oct 2022 08:40:48 +0000 のような値を出力
echo $date->format(DateTimeInterface::RFC2822), "\n";
?>

フォーマット文字列の中で既知の文字が展開されることを防ぐために、 バックスラッシュでエスケープすることができます。 バックスラッシュ付きの文字が既に特殊な意味を持つ場合は、 バックスラッシュもエスケープする必要があるでしょう。

例3 フォーマット中に文字をエスケープする

<?php
$date
= new DateTimeImmutable();
// prints something like: Wednesday the 19th
echo $date->format('l \t\h\e jS');
?>

他の言語で日付をフォーマットするには、 DateTimeInterface::format() ではなく IntlDateFormatter::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
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