PHP Conference Japan 2024

strftime

(PHP 4, PHP 5, PHP 7, PHP 8)

strftime根據地區設定格式化當地時間/日期

警告

此函式自 PHP 8.1.0 起已遭 *棄用*。強烈建議不要依賴此函式。

此函式的替代方案包括

說明

#[\Deprecated]
strftime(字串 $format, ?整數 $timestamp = null): 字串|false

根據地區設定格式化時間和/或日期。月份和星期名稱以及其他語言相關的字串會遵循使用 setlocale() 設定的目前地區設定。

警告

並非所有轉換規範符都受到您的 C 函式庫支援,在這種情況下,PHP 的 strftime() 也不會支援它們。此外,並非所有平台都支援負的時間戳記,因此您的日期範圍可能被限制在 Unix 紀元之後。這意味著 %e、%T、%R 和 %D(以及可能其他的) - 以及早於 1970 年 1 月 1 日 的日期 - 在 Windows、某些 Linux 發行版和其他一些作業系統上將無法正常運作。對於 Windows 系統,可以在 » MSDN 找到受支援轉換規範符的完整概述。請改用 IntlDateFormatter::format() 方法。

參數

format

以下字元在 format 參數字串中會被識別
format 說明 範例回傳值
--- ---
%a 星期的縮寫文字表示法 SunSat
%A 星期的完整文字表示法 SundaySaturday
%d 月份中的日期,兩位數(包含前導零) 0131
%e 月份中的日期,個位數前面有一個空格。在 Windows 上未按說明實作。有關更多資訊,請參見下文。 131
%j 一年中的第幾天,三位數,包含前導零 001366
%u 星期幾的 ISO-8601 數字表示法 1(星期一)到 7(星期日)
%w 星期幾的數字表示法 0(星期日)到 6(星期六)
--- ---
%U 指定年份的週數,以第一個星期日作為第一週開始 13(代表一年中的第 13 週)
%V 指定年份的 ISO-8601:1988 週數,從一年中至少有 4 個工作日的第一週開始,星期一為一週的開始 0153(其中 53 表示重疊的週)
%W 一年中週數的數字表示法,以第一個星期一作為第一週開始 46(代表一年中以星期一開始的第 46 週)
--- ---
%b 月份名稱縮寫,根據地區設定而定 JanDec
%B 完整的月份名稱,根據地區設定而定 JanuaryDecember
%h 月份名稱縮寫,根據地區設定而定(%b 的別名) JanDec
%m 月份的兩位數表示法 01(一月)到 12(十二月)
--- ---
%C 世紀的兩位數表示法(年份除以 100,截斷為整數) 19 代表 20 世紀
%g 根據 ISO-8601:1988 標準的年份兩位數表示法(參見 %V) 範例:09 代表 2009 年 1 月 6 日的週
%G %g 的完整四位數版本 範例:2008 代表 2009 年 1 月 3 日的週
%y 年份的兩位數表示法 範例:09 代表 2009 年,79 代表 1979 年
%Y 年份的四位數表示法 範例:2038
時間 --- ---
%H 24 小時制的小時兩位數表示法 0023
%k 24 小時制的時,個位數前面會加空格 023
%I 12 小時制的時,兩位數表示 0112
%l (小寫 'L') 12 小時制的時,個位數前面會加空格 112
%M 分的兩位數表示 0059
%p 根據指定時間顯示大寫「AM」或「PM」 範例:00:31 為 AM,22:23 為 PM。確切結果取決於作業系統,也可能返回小寫變體或帶點的變體(例如 a.m.)。
%P 根據指定時間顯示小寫「am」或「pm」 範例:00:31 為 am,22:23 為 pm。並非所有作業系統都支援。
%r 與 "%I:%M:%S %p" 相同 範例:21:34:17 為 09:34:17 PM
%R 與 "%H:%M" 相同 範例:12:35 AM 為 00:35,4:44 PM 為 16:44
%S 秒的兩位數表示 0059
%T 與 "%H:%M:%S" 相同 範例:09:34:17 PM 為 21:34:17
%X 根據地區設定的慣用時間表示法,不含日期 範例:03:59:1615:59:16
%z 時區偏移量。在 Windows 上的實作與說明不同。詳情請見下文。 範例:美國東部時間為 -0500
%Z 時區縮寫。在 Windows 上的實作與說明不同。詳情請見下文。 範例:東部時間為 EST
時間和日期戳記 --- ---
%c 根據地區設定的慣用日期和時間戳記 範例:2009 年 2 月 5 日 12:45:10 AM 為 Tue Feb 5 00:45:10 2009
%D 與 "%m/%d/%y" 相同 範例:2009 年 2 月 5 日為 02/05/09
%F 與 "%Y-%m-%d" 相同(常用於資料庫日期戳記) 範例:2009 年 2 月 5 日為 2009-02-05
%s Unix Epoch 時間戳記(與 time() 函式相同) 範例:1979 年 9 月 10 日 08:40:00 AM 為 305815200
%x 根據地區設定的慣用日期表示法,不含時間 範例:2009 年 2 月 5 日為 02/05/09
其他 --- ---
%n 換行字元 ("\n") ---
%t Tab 字元 ("\t") ---
%% 字面百分比字元 ("%") ---

警告

與 ISO-9899:1999 不同,Sun Solaris 以星期日為 1。因此,%u 的功能可能與本手冊中的說明不同。

警告

僅限 Windows

此函式的 Windows 實作不支援 %e 修飾符。要取得此值,可以使用 %#d 修飾符代替。以下範例說明如何編寫跨平台相容的函式。

%z%Z 修飾符都會返回時區名稱,而不是偏移量或縮寫。

警告

僅限 macOS 和 musl: macOS 此函式的 macOS 實作不支援 %P 修飾符。

時間戳記

選用的 timestamp 參數是一個 int Unix 時間戳記,如果省略 timestamp 或其為 null,則預設為目前的當地時間。換句話說,它預設為 time() 的值。

傳回值

根據給定的 format 格式字串,返回格式化後的字串。若未提供 timestamp 時間戳記,則使用目前的本地時間。月份、星期名稱和其他與語言相關的字串會遵循使用 setlocale() 設定的當前語系。如果 format 為空、包含不支援的轉換規範,或者返回的字串長度超過 4095,則函數會返回 false

錯誤/例外

如果時區無效,每次呼叫日期/時間函數都會產生 E_WARNING 警告。另請參閱 date_default_timezone_set()

由於輸出取決於底層的 C 函式庫,因此某些轉換規範不支援。在 Windows 上,提供未知的轉換規範將會導致 5 個 E_WARNING 警告訊息並返回 false。在其他作業系統上,您可能不會收到任何 E_WARNING 警告訊息,且輸出可能包含未轉換的轉換規範。

更新日誌

版本 說明
8.0.0 timestamp 現在可以為 null。

範例

如果您在系統中安裝了相應的語系,則以下範例將會正常運作。

範例 #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";

?>

範例 #3 使用 %e 修飾符的跨平台相容範例

<?php

// 1 月 1 日:結果為:'%e%1%' (%%, e, %%, %e, %%)
$format = '%%e%%%e%%';

// 檢查是否為 Windows 系統,以便正確地搜尋和替換 %e
// 修飾符
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$format = preg_replace('#(?<!%)((?:%%)*)%e#', '\1%#d', $format);
}

echo
strftime($format);
?>

範例 #4 顯示所有已知和未知的格式

<?php

// Describe the formats
$strftimeFormats = array(
'A' => 'A full textual representation of the day',
'B' => 'Full month name, based on the locale',
'C' => 'Two digit representation of the century (year divided by 100, truncated to an integer)',
'D' => 'Same as "%m/%d/%y"',
'E' => '',
'F' => 'Same as "%Y-%m-%d"',
'G' => 'The full four-digit version of %g',
'H' => 'Two digit representation of the hour in 24-hour format',
'I' => 'Two digit representation of the hour in 12-hour format',
'J' => '',
'K' => '',
'L' => '',
'M' => 'Two digit representation of the minute',
'N' => '',
'O' => '',
'P' => 'lower-case "am" or "pm" based on the given time',
'Q' => '',
'R' => 'Same as "%H:%M"',
'S' => 'Two digit representation of the second',
'T' => 'Same as "%H:%M:%S"',
'U' => 'Week number of the given year, starting with the first Sunday as the first week',
'V' => 'ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week',
'W' => 'A numeric representation of the week of the year, starting with the first Monday as the first week',
'X' => 'Preferred time representation based on locale, without the date',
'Y' => 'Four digit representation for the year',
'Z' => 'The time zone offset/abbreviation option NOT given by %z (depends on operating system)',
'a' => 'An abbreviated textual representation of the day',
'b' => 'Abbreviated month name, based on the locale',
'c' => 'Preferred date and time stamp based on local',
'd' => 'Two-digit day of the month (with leading zeros)',
'e' => 'Day of the month, with a space preceding single digits',
'f' => '',
'g' => 'Two digit representation of the year going by ISO-8601:1988 standards (see %V)',
'h' => 'Abbreviated month name, based on the locale (an alias of %b)',
'i' => '',
'j' => 'Day of the year, 3 digits with leading zeros',
'k' => 'Hour in 24-hour format, with a space preceding single digits',
'l' => 'Hour in 12-hour format, with a space preceding single digits',
'm' => 'Two digit representation of the month',
'n' => 'A newline character ("\n")',
'o' => '',
'p' => 'UPPER-CASE "AM" or "PM" based on the given time',
'q' => '',
'r' => 'Same as "%I:%M:%S %p"',
's' => 'Unix Epoch Time timestamp',
't' => 'A Tab character ("\t")',
'u' => 'ISO-8601 numeric representation of the day of the week',
'v' => '',
'w' => 'Numeric representation of the day of the week',
'x' => 'Preferred date representation based on locale, without the time',
'y' => 'Two digit representation of the year',
'z' => 'Either the time zone offset from UTC or the abbreviation (depends on operating system)',
'%' => 'A literal percentage character ("%")',
);

// Results
$strftimeValues = array();

// Evaluate the formats whilst suppressing any errors
foreach ($strftimeFormats as $format => $description) {
if (
false !== ($value = @strftime("%{$format}"))) {
$strftimeValues[$format] = $value;
}
}

// Find the longest value
$maxValueLength = 2 + max(array_map('strlen', $strftimeValues));

// Report known formats
foreach ($strftimeValues as $format => $value) {
echo
"Known format : '{$format}' = ", str_pad("'{$value}'", $maxValueLength), " ( {$strftimeFormats[$format]} )\n";
}

// Report unknown formats
foreach (array_diff_key($strftimeFormats, $strftimeValues) as $format => $description) {
echo
"Unknown format : '{$format}' ", str_pad(' ', $maxValueLength), ($description ? " ( {$description} )" : ''), "\n";
}

?>

以上範例將輸出類似以下內容:

Known format   : 'A' = 'Friday'            ( A full textual representation of the day )
Known format   : 'B' = 'December'          ( Full month name, based on the locale )
Known format   : 'H' = '11'                ( Two digit representation of the hour in 24-hour format )
Known format   : 'I' = '11'                ( Two digit representation of the hour in 12-hour format )
Known format   : 'M' = '24'                ( Two digit representation of the minute )
Known format   : 'S' = '44'                ( Two digit representation of the second )
Known format   : 'U' = '48'                ( Week number of the given year, starting with the first Sunday as the first week )
Known format   : 'W' = '48'                ( A numeric representation of the week of the year, starting with the first Monday as the first week )
Known format   : 'X' = '11:24:44'          ( Preferred time representation based on locale, without the date )
Known format   : 'Y' = '2010'              ( Four digit representation for the year )
Known format   : 'Z' = 'GMT Standard Time' ( The time zone offset/abbreviation option NOT given by %z (depends on operating system) )
Known format   : 'a' = 'Fri'               ( An abbreviated textual representation of the day )
Known format   : 'b' = 'Dec'               ( Abbreviated month name, based on the locale )
Known format   : 'c' = '12/03/10 11:24:44' ( Preferred date and time stamp based on local )
Known format   : 'd' = '03'                ( Two-digit day of the month (with leading zeros) )
Known format   : 'j' = '337'               ( Day of the year, 3 digits with leading zeros )
Known format   : 'm' = '12'                ( Two digit representation of the month )
Known format   : 'p' = 'AM'                ( UPPER-CASE "AM" or "PM" based on the given time )
Known format   : 'w' = '5'                 ( Numeric representation of the day of the week )
Known format   : 'x' = '12/03/10'          ( Preferred date representation based on locale, without the time )
Known format   : 'y' = '10'                ( Two digit representation of the year )
Known format   : 'z' = 'GMT Standard Time' ( Either the time zone offset from UTC or the abbreviation (depends on operating system) )
Known format   : '%' = '%'                 ( A literal percentage character ("%") )
Unknown format : 'C'                       ( Two digit representation of the century (year divided by 100, truncated to an integer) )
Unknown format : 'D'                       ( Same as "%m/%d/%y" )
Unknown format : 'E'
Unknown format : 'F'                       ( Same as "%Y-%m-%d" )
Unknown format : 'G'                       ( The full four-digit version of %g )
Unknown format : 'J'
Unknown format : 'K'
Unknown format : 'L'
Unknown format : 'N'
Unknown format : 'O'
Unknown format : 'P'                       ( lower-case "am" or "pm" based on the given time )
Unknown format : 'Q'
Unknown format : 'R'                       ( Same as "%H:%M" )
Unknown format : 'T'                       ( Same as "%H:%M:%S" )
Unknown format : 'V'                       ( ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week )
Unknown format : 'e'                       ( Day of the month, with a space preceding single digits )
Unknown format : 'f'
Unknown format : 'g'                       ( Two digit representation of the year going by ISO-8601:1988 standards (see %V) )
Unknown format : 'h'                       ( Abbreviated month name, based on the locale (an alias of %b) )
Unknown format : 'i'
Unknown format : 'k'                       ( Hour in 24-hour format, with a space preceding single digits )
Unknown format : 'l'                       ( Hour in 12-hour format, with a space preceding single digits )
Unknown format : 'n'                       ( A newline character ("\n") )
Unknown format : 'o'
Unknown format : 'q'
Unknown format : 'r'                       ( Same as "%I:%M:%S %p" )
Unknown format : 's'                       ( Unix Epoch Time timestamp )
Unknown format : 't'                       ( A Tab character ("\t") )
Unknown format : 'u'                       ( ISO-8601 numeric representation of the day of the week )
Unknown format : 'v'

注意事項

注意 基於 ISO 8601:1988 週數的 %G 和 %V,如果沒有完全理解其編號系統,可能會產生出乎意料(儘管正確)的結果。請參閱本手冊頁面中的 %V 範例。

參見

新增註釋

使用者貢獻的註釋 1 則註釋

divinity76+spam at gmail dot com
1 年前
https://github.com/alphp/strftime 有一個適用於 php>=8.1 的 strftime 相容性套件
To Top