PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

strptime> <mktime
Last updated: Fri, 04 Jul 2008

view this page in

strftime

(PHP 4, PHP 5)

strftime — ロケールの設定に基づいてローカルな日付・時間をフォーマットする

説明

string strftime ( string $format [, int $timestamp ] )

ローカルの時刻・日付を、ロケール設定にもとづいてフォーマットします。 月および曜日の名前、およびその他の言語依存の文字列は、 setlocale() で設定された現在のロケールを尊重して表示されます。

使用する C ライブラリで、すべての変換指定子がサポートされているとは限りません。 そのような場合、該当する変換指定子は PHP の strftime() ではサポートされません。 また、全てのプラットフォームが負のタイムスタンプをサポートしているわけではないため、 Unix Epoch (1970 年 1 月 1 日)以前の日付を扱えないかもしれません。 つまり、Windows や一部の Linux ディストリビューション、そしてその他のごく一部の オペレーティングシステム上では %e、%T、%R および %D (あるいはこれ以外も) が Jan 1, 1970 より前の日付について動作しないということです。 Windwos システム上でサポートされる変換指定子の概要については、 » MSDN のウェブサイト に掲載されています。

パラメータ

format

次の変換指定子は、フォーマット文字列として認識されます。

  • %a - 現在のロケールに基づく短縮された曜日の名前
  • %A - 現在のロケールに基づく完全な曜日の名前
  • %b - 現在のロケールに基づく短縮された月の名前
  • %B - 現在のロケールに基づく完全な月の名前
  • %c - 現在のロケールに基づく適当な日付と時間の表現
  • %C - 世紀 (年を 100 で割り、整数に丸めたもの。00 から 99)
  • %d - 日付を 10 進数で (01 から 31)。
  • %D - %m/%d/%y と同じ
  • %e - 月単位の日付を 10 進数で表したもの。日付が 1 桁の場合は、 前に空白を一つ付けます (' 1' から '31')。
  • %g - 世紀以外は %G と同じ。
  • %G - ISO 週番号 (%V を参照) に対応する 4 桁の年。 これは ISO 週番号が前年もしくは次年に属するかによって使用される年が 異なる事を除き %Y と同じフォーマットと値です。
  • %h - %bと同じ。
  • %H - 時間を 24 時間表示の 10 進数で (00 から 23 まで)。
  • %I - 時間を 12 時間表示の 10 進数で (01 から 12 まで)。
  • %j - 年間での日付を 10 進数で表現 (001 から 366)。
  • %m - 月を 10 進数で表現 (01 から 12)。
  • %M - 分を 10 進数で表現。
  • %n - 改行文字。
  • %p - 指定した時間により `am' または `pm'、 または現在のロケールの、それに対応する文字列。
  • %r - a.m. および p.m. 表記で表した時間。
  • %R - 24 時間表記で表した時間。
  • %S - 秒を 10 進数で表現。
  • %t - タブ文字。
  • %T - 現在の時間。%H:%M:%S に等しい。
  • %u - 10 進数表記の曜日。1 から 7 の範囲で表し、1 が月曜日。
    警告

    Sun Solaris では日曜日を 1 と表しているようですが、 ISO 9889:1999 (現在の C 言語の標準規格) では「1 は月曜日」と明確に指定されています。

  • %U - 年間で何番目の週であるかを 10 進数で表現。 年間で最初の日曜を最初の週の最初の日として数えます。
  • %V - ISO 8601:1988 で規定された現在の年の週番号の 10 進数表現で、 01 から 53 までの範囲となります。1 は最初の週で、その週は現在の年に 最低 4 日はあります。週は月曜日から始まります (指定したタイムスタンプの週番号に対応する年を表すには、 %G あるいは %g をしてください)。
  • %W - 現在の年で何番目の週であるかを 10 進数で表現。 年間で最初の月曜を最初の週の最初の日として数えます。
  • %w - 曜日を 10 進数で表現。日曜は 0 になります。
  • %x - 時間を除いた日付を現在のロケールに基づき表現します。
  • %X - 日付を除いた時間を現在のロケールに基づき表現します。
  • %y - 世紀の部分を除いた年を10進数として表現 (00 から 99 までの範囲)。
  • %Y - 世紀を含む年を 10 進数で表現。
  • %Z あるいは %z - タイムゾーンまたはその名前または短縮形。
  • %% - 文字リテラル`%'。

このパラメータの最大長は 1023 文字です。

timestamp

オプションのパラメータ timestamp は、 integer 型の Unix タイムスタンプです。 timestamp が指定されなかった場合のデフォルト値は、 現在の時刻です。言い換えると、デフォルトは time() の返り値となります。

返り値

指定した timestamp または timestamp が指定されていない場合に現在のローカル時間を用いて、 指定したフォーマット文字列に基づき文字列をフォーマットして返します。 月および曜日の名前、およびその他の言語依存の文字列は、 setlocale() で設定された現在のロケールを尊重して表示されます。

エラー / 例外

すべての日付/時刻関数は、 有効なタイムゾーンが設定されていない場合に E_NOTICE を発生させます。また、システム設定のタイムゾーンあるいは環境変数 TZ を使用した場合には E_STRICT を発生させます。 date_default_timezone_set() も参照ください。

変更履歴

バージョン 説明
5.1.0

タイムゾーンがおかしい場合に E_STRICTE_NOTICE が発生するようになりました。

この例は、それぞれのロケールがシステムにインストールされている場合にのみ動作します。

例1 strftime() のロケールの例

<?php
setlocale
(LC_TIME"C");
echo 
strftime("%A");
setlocale(LC_TIME"fi_FI");
echo 
strftime(" in Finnish is %A,");
setlocale(LC_TIME"fr_FR");
echo 
strftime(" in French %A and");
setlocale(LC_TIME"de_DE");
echo 
strftime(" in German %A.\n");
?>

例2 ISO 8601:1988 の週番号の例

<?php
/*     December 2002 / January 2003
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     16  17  18  19  20  21  22
52     23  24  25  26  27  28  29
1      30  31   1   2   3   4   5
2       6   7   8   9  10  11  12
3      13  14  15  16  17  18  19   */

// Outputs: 12/28/2002 - %V,%G,%Y = 52,2002,2002
echo "12/28/2002 - %V,%G,%Y = " strftime("%V,%G,%Y"strtotime("12/28/2002")) . "\n";

// Outputs: 12/30/2002 - %V,%G,%Y = 1,2003,2002
echo "12/30/2002 - %V,%G,%Y = " strftime("%V,%G,%Y"strtotime("12/30/2002")) . "\n";

// Outputs: 1/3/2003 - %V,%G,%Y = 1,2003,2003
echo "1/3/2003 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/3/2003")) . "\n";

// Outputs: 1/10/2003 - %V,%G,%Y = 2,2003,2003
echo "1/10/2003 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/10/2003")) . "\n";



/*     December 2004 / January 2005
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     13  14  15  16  17  18  19
52     20  21  22  23  24  25  26
53     27  28  29  30  31   1   2
1       3   4   5   6   7   8   9
2      10  11  12  13  14  15  16   */

// Outputs: 12/23/2004 - %V,%G,%Y = 52,2004,2004
echo "12/23/2004 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("12/23/2004")) . "\n";

// Outputs: 12/31/2004 - %V,%G,%Y = 53,2004,2004
echo "12/31/2004 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("12/31/2004")) . "\n";

// Outputs: 1/2/2005 - %V,%G,%Y = 53,2004,2005
echo "1/2/2005 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/2/2005")) . "\n";

// Outputs: 1/3/2005 - %V,%G,%Y = 1,2005,2005
echo "1/3/2005 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/3/2005")) . "\n";

?>

注意

注意: ISO 8601:1988 week numbers に基づいている %G と %V は、 もしナンバリングシステムが完全に理解されていなければ 期待とは違う結果をもたらします。 このマニュアルの %V の例を参照ください。



strptime> <mktime
Last updated: Fri, 04 Jul 2008
 
add a note add a note User Contributed Notes
strftime
contact_ at _line-o_ dot _de
10-May-2008 05:45
You can get MS locale strings from here now:

http://msdn.microsoft.com/de-de/library/cdax410z.aspx

Search for "country codes" or "region codes", if they move it again!

(see below...)
Josue R.
09-Mar-2008 12:36
Here's a simple version for date formating i use between displaying in HTML and converting back to MYSQL format:

function format_date($original='', $format="%m/%d/%Y") {
    $format = ($format=='date' ? "%m-%d-%Y" : $format);
    $format = ($format=='datetime' ? "%m-%d-%Y %H:%M:%S" : $format);
    $format = ($format=='mysql-date' ? "%Y-%m-%d" : $format);
    $format = ($format=='mysql-datetime' ? "%Y-%m-%d %H:%M:%S" : $format);
    return (!empty($original) ? strftime($format, strtotime($original)) : "" );
}

example (in HTML or webapp):
[grab from database]...
$dbase_stored_date = "2007-03-15";
$display_html_date = format_date($dbase_stored_date);
... displays as "03/15/2007"

example (saving form via on POST/GET):
$update_date = format_date($_POST['display_html_date'], 'mysql-date');
// converts back to '2007-03-15'
.... [your mysql update here]

Don't forget to sanitize your POST/GET's   =)
Anonymous
25-Feb-2008 09:08
%u doesn't work under MS Windows. But getDate()['wday'] works as a perfekt workaround.
Anonymous
24-Feb-2008 04:01
If the second parameter is null, PHP treats it as 0, so strftime return something like 01/01/1970. Be aware of this.
jerome dot place at free dot fr
08-Nov-2007 05:55
Here is a function to convert dates before 1970, very useful if you are still using php 4 (it is supported in php5) :

# convert a date to special format
# $date is like 2000-01-01 00:00:00
# $format : refer to strftime function
function convert_date($date,$format) {   
    if($date=='0000-00-00 00:00:00' OR $date=='0000-00-00' OR $date=='' OR $date==NULL) {
        return '';
    }
    else {
        $year=substr($date,0,4);
        if(phpversion() < 5.0 AND $year < 1970) {
           
            $new_date=substr_replace($date,'1980',0,4); # we replace the year by a year after 1970       
            $new_format=eregi_replace('%a|%A|%u','',$format); # we remove days information from the format because they would be wrong
            $new_date=strftime($new_format,strtotime($new_date)); # we convert the date
            $new_date=eregi_replace('1980',$year,$new_date); # we put back the real year
            return $new_date;
        }
        else {
            return strftime($format,strtotime($date));
        }
    }
}
josh dot helzer at gmail dot com
19-Sep-2007 11:39
If strlen($format) >= 1024, the output of strftime($format) is the empty string.
nielsvan den berge at hotmail dot com
31-Aug-2007 10:43
A small function to get the first weekday of the month.
For example the first monday of the month, or the first friday, etc.

<?php 
 
/**
   *
   *  Gets the first weekday of that month and year
   *
   *  @param  int   The day of the week (0 = sunday, 1 = monday ... , 6 = saturday)
   *  @param  int   The month (if false use the current month)
   *  @param  int   The year (if false use the current year)
   *
   *  @return int   The timestamp of the first day of that month
   *
   **/ 
 
function get_first_day($day_number=1, $month=false, $year=false)
  {
   
$month  = ($month === false) ? strftime("%m"): $month;
   
$year   = ($year === false) ? strftime("%Y"): $year;
   
   
$first_day = 1 + ((7+$day_number - strftime("%w", mktime(0,0,0,$month, 1, $year)))%7);
 
    return
mktime(0,0,0,$month, $first_day, $year);
  }

// this will output the first wednesday of january 2007 (wed 03-01-2007)
echo strftime("%a %d-%m-%Y", get_first_day(3, 1, 2007));
?>
ma
28-Aug-2007 09:58
note, that for some languages you MUST set LC_ALL instead of LC_TIME.

note that you further have to explicitly define your output-encoding (default is ISO-8859-1 [which makes problems for some languages])!

at least i expirienced this behaviour on a german WinXP-PHP4 environment:

<?php

// does not work - gives question marks:
setlocale(LC_TIME, 'RUS'); // ISO Alpha-3 is supported by xp
echo strftime('%A', time());

?>

<?php

// DOES work:
header('Content-Type: text/html; charset=UTF-8'); // you could also use another charset here if iconv isn't installed on your system.

echo setlocale(LC_ALL, 'RUS').': ';
echo
iconv('windows-1251', 'UTF-8', strftime('%A', time()))."\n";

?>
ben dot holland at thirdlight dot com
21-Jun-2007 09:03
This little function allows you to provide a reasonably human readable string and convert to a timestamp - see example in comments below.

I find it far more useful than having to remember all the '%' modifiers. Am also well aware of its failings but it works in a lot of the real life situations I've come across.

<?php
function AmazingStringFromTime($str, $nTimestamp = null)
{
   
// This function reads a human readable string representation of dates. e.g.
    // DD MM YYYY => 01 07 1978
    // DDD D MMM YY => Mon 1 Jul 78
   
   
$arrPairs = array(
   
"DDDD"  => "%A",
   
"DDD"   => "%a",
   
"DD"    => "%d",
   
"D"     => "%e", // has leading space: ' 1', ' 2', etc for single digit days
   
"MMMM"  => "%B",
   
"MMM"   => "%b",
   
"MM"    => "%m",
   
"YYYY"  => "%Y",
   
"YY"    => "%y",
   
"HH"    => "%H",
   
"hh"    => "%I",
   
"mm"    => "%M",
   
"ss"    => "%S",
    );
   
   
$str = str_replace(array_keys($arrPairs), array_values($arrPairs), $str);
    return
strftime($str, $nTimestamp);
}
?>
th1nk3r at gmail dot DELETETHIS dot com
21-Jan-2007 02:35
Function strftime() use the locales installed in your system (linux).

If you are like me and only leave in the system the locales you use normally (en_US and your own language locale, like es_ES), you'll only be able to use the locales installed. If your application is translated to other languages, you need these locales too.

The name of the locale in your system is important too. This can be a problem when you want to distribute the app.

If you have this locales in your system:
en_US/ISO-8859-1
en_US.UTF-8/UTF-8
es_ES/ISO-8859-1
es_ES@euro/ISO-8859-15
es_ES.UTF-8/UTF-8
es_ES@euro/UTF-8

and use setlocale('es_ES'), the result will use the iso-8859-1 charset even if you have all your system, files and configuration options in UTF-8. To receive content in UTF-8, in this example, you need to use setlocale('es_ES.UTF-8') or setlocale('es_ES.UTF-8@UTF-8').

The definition of locales can change from one system to another, and so the charset from the results.
denis at spiralsolutions dot com
02-Nov-2006 05:07
(in addition to Andy's post)
To get a RFC 2822 date (used in RSS) of the current local time :

echo strftime ("%a, %d %b %Y %H:%M:%S %z") ;

Note: option %z / %Z - work different on Windows platform, for example
output of this code line can be:
Thu, 02 Nov 2006 09:54:59 Jerusalem Standard Time (on Windows)
Thu, 02 Nov 2006 09:54:59 +0200                   (on Linux)

[red. It is much smarter to use date(DATE_RSS); here]
Moritz Stoltenburg
18-Aug-2006 12:45
In response to the note supplied by "Arpad Borsos":

I think the whole truth is that the output of strftime() considers whatever you stated with setlocale().

<?php

/* Berlin is in Germany */
$locale = setlocale (LC_ALL, 'de_DE.UTF-8');

/* Output: Donnerstag, 23. März 2006 (and hopefully UTF-8 ;) */
echo strftime ("%A, %d. %B %Y", strtotime('2006-03-23'));

/* try different possible locale names for german as of PHP 4.3.0 */
$locale = setlocale(LC_ALL, 'de_DE.UTF-8', 'de_DE.UTF-8@euro', 'de_DE');
echo
"Preferred locale for german on this system is '$locale'";

?>

Check the documentation of setlocale() for more.
setlocale (LC_ALL, 'de_DE.UTF-8') always worked fine for me.
Arpad Borsos
17-Aug-2006 08:32
Please note that the strftime output is not encoded in utf8 so you have to use utf8_encode() if you want to print localized month names e.g. for German "März"

[red. this depends on the platform though - some Windows locales *do* use UTF-8 for example]
reeveboy at hotmail dot com
28-Jul-2006 01:01
To mcallister, phloe and anyone else who want to get on the getDaySuffix() band wagon:

There are already functions to do this. All you really have to do is:

<?=date("jS", mktime(0,0,0,1,$myDay,2006))?>

Obviously, the only part of mktime that really matters is $myDay.
Moritz Stoltenburg
23-Jul-2006 02:54
In response to the note supplied by "segfault nycap rr com".

Here is a quicker and easier way:

Use the MySQL Time Function TIME_FORMAT() in your query:

mysql> SELECT TIME_FORMAT('14:35:00', '%l:%i %p');

Or try '%l' in PHP, it works on most systems and is part of the Open Group specification of strftime().

<?php

echo strftime('%l:%M %p', strtotime('14:35:00'));

?>
andy at yatescentral dot com
17-May-2006 12:47
When using strftime to generate time stamps for inclusion in  RSS feeds, be sure to use %z for the timezone (RFC-822 format) rather than %Z -- for some reason, %Z fails to validate.
posenato at sciNO dot univrSPAM dot it
15-May-2006 03:37
To partialy correct Neo's on RFC 850 date...

RFC 850 is obsolete by RFC 1036.

In HTTP header, RFC 1123 is the first choice: it has a fixed length format and 4 digits year.

Therefore, the correct format is:

gmstrftime ("%a, %d %b %Y %T %Z", time ());

Output example: Sun, 06 Nov 1994 08:49:37 GMT

[red. Use date(DATE_RFC850, time()); instead. (Or DATE_RFC1123 or DATE_RFC1036)]
Jon Keating
18-Jan-2006 10:49
Under windows if you are using Japanese version, you must use the following code:

setlocale(LC_ALL, "Japanese_Japan.20932") for EUC
setlocale(LC_ALL, "Japanese_Japan.932") for SJIS

I found the following page that helped me with this issue:
http://moodle.org/mod/forum/discuss.php?d=8329
php at REMOVEMEkennel17 dot co dot uk
20-Dec-2005 09:29
To correct an error in the above list of formatting codes:

%p - either `AM' or `PM' according to the given time value, or the corresponding strings for the current locale (note result is in capitals)
%P - either `am' or `pm' according to the given time value, or the corresponding strings for the current locale (note result is in lower case)

In addition, the following codes seem to return a value on my system (Linux, Apache/1.3.33, PHP/4.4.1), but are not documented above.  I have included the result given by passing them to gmstrftime() with a timestamp of 0 (unix epoch).  gmstrftime() was used to avoid timezone/DST differences.

%F: "1970-01-01" (appears to be an SQL-formatted version of the date)
%k: "0" (seems to be the hour in 24-hour clock, without leading zeros (space-padded))
%l: "12" (seems to be the hour in 12-hour clock, without leading zeros (space-padded))
%s: "-3600"

%s seems to be the Unix timestamp passed to the function, but somehow based on the current locale/TZ settings (even in gmstrftime()). 
On my system strftime("%H:%M:%S", 0) returns "01:00:00", and strftime("%s", 0) returns "0".  Using gmstrftime() I get "00:00:00" and "-3600" respectively.
jw at jwscripts dot com
29-May-2005 10:32
The following function implements the conversion specifiers which are not supported on Win32 platforms:

(Note: the specifiers %V, %G and %g can be implemented using other functions described in this section)

<?php

function strftime_win32($format, $ts = null) {
    if (!
$ts) $ts = time();

   
$mapping = array(
       
'%C' => sprintf("%02d", date("Y", $ts) / 100),
       
'%D' => '%m/%d/%y',
       
'%e' => sprintf("%' 2d", date("j", $ts)),
       
'%h' => '%b',
       
'%n' => "\n",
       
'%r' => date("h:i:s", $ts) . " %p",
       
'%R' => date("H:i", $ts),
       
'%t' => "\t",
       
'%T' => '%H:%M:%S',
       
'%u' => ($w = date("w", $ts)) ? $w : 7
   
);
   
$format = str_replace(
       
array_keys($mapping),
       
array_values($mapping),
       
$format
   
);

    return
strftime($format, $ts);
}

?>
patrick at codeministry dot dk
20-Apr-2005 06:50
For freebsd user:

You can find the full list of your locale under /usr/share/locale.
For example da_DK.ISO8859-1 under this directory will set up the locale to danish.
bohac at smartcat dot cz
20-Mar-2005 03:36
i had to use the czech representation of time on unix machine, running debian and linux version of apache with php 4

for me the best solution was to use this code:

<php
     setlocale(LC_ALL, 'cs_CZ.iso88592');
?>

then you can do everything in czech language with correct iso-8859-2 encoding ;D
Aaron
26-Jan-2005 06:10
%k will give you %H (hour, 24-hour clock) with the leading zero replaced by a space.  I have only tested this on one linux system so far, it may not work on windows or other linux builds.
michiel1978 at hotmail dot com
07-Oct-2004 06:31
As said in these comments, Windows strftime() doesn't support %e. However, to achieve a similar effect (not 100%) you can use %#d. The # flag will remove the leading zero, so you do get single digits, but without the space that would be added by %e in other environments.
neo at gothic-chat d0t de
25-Jun-2004 03:27
To get a RFC 850 date (used in HTTP) of the current time:

gmstrftime ("%A %d-%b-%y %T %Z", time ());

This will get for example:
Friday 25-Jun-04 03:30:23 GMT

Please note that times in HTTP-headers _must_ be GMT, so use gmstrftime() instead of strftime().
adan at cr72 dot com
10-Jun-2004 08:48
For Spanish:
<?
setlocale
(LC_ALL, "sp");
echo
strftime("%d. %B %Y");
?>
php_manual at it-rex dot nl
29-Mar-2004 10:31
In the strftime override-function of rickenmeer at hotmail dot com there is an error.

The line:
  $year = 1969;
should read:
  $year = 1970;
vminarik at ips-ag dot cz
10-Sep-2001 10:02
Note that setting LC_TIME is not enough for some locales under Windows, e.g. Czech, because there are some characters not contained in default (US) character set like '' (c with hook), '' (r with hook).


If you run Apache as regular application and have set your locale to Czech (ControlPanel/RegionalOptions), there is no problem and 'September' is correctly translated as 'z', 'Thursday' as 'tvrtek'.
But if you run Apache as service, you get 'zr', and 'ctvrtek'.
To get things work as you expect you must set LC_CTYPE beside LC_TIME, or set LC_ALL.

<?
  $locale
= 'Czech_Czech.1250';
 
$res = setlocale( 'LC_CTYPE', $locale); //important
 
$res = setlocale( 'LC_TIME', $locale);
  echo
strftime( '%A %m. %B %Y', mktime( 0,0,0,9,6,2001));
?>
verdy_p at wanadoo dot fr
22-Jul-2001 09:33
Beware of '%D':
the comment shown expects that this is the same as '%m/%d/%y'.

This is wrong: '%D' is only expected to returned an abbreviated numeric date according to the current locale:
In the German locale '%D' is '%y.%m.%d'
In the French locale '%D' is '%d/%m/%y'

The locale rules still apply to %D as with '%A'...

Beware that some C libraries do not support '%D' and/or '%A'  or do not support them accordingly. Using strftime() is then system-dependant, because PHP use the C function provided by the system on which it runs.
spamyenot at example dot com
19-Jul-2001 03:09
Solaris 2.6 and 7 define the
%u specifier differently than noted here. Day 1 is Sunday, not Monday. Solaris 8 gets it right.

Jim
zmajeed at cup dot hp dot com
23-Jul-1999 07:14
Locale names are OS dependent. HP-UX 11.0, for example, has three
German locales, de_DE.roman8, de_DE.iso88591, and
de_DE.iso885915@euro.
The command locale -a will display all available locales on a system.

So on HP-UX, to get German dates:
setlocale("LC_TIME", "de_DE.roman8");
print(strftime("%A\n"));

strptime> <mktime
Last updated: Fri, 04 Jul 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites