在 PHP 中使用 Date() 函式獲取當前月份
Subodh Poudel
2022年5月13日
PHP
PHP DateTime
本教程介紹了在 PHP 中查詢當前月份的方法。
在 PHP 中使用 date() 函式查詢當前月份
我們可以使用 PHP 中的 date() 函式根據提供的格式獲取當前日期。date() 函式的語法如下所示。
date($format,$timestamp);
$format 選項指示日期的格式。我們可以設定 DateTimeInterface 類的 format() 方法支援的格式。 $format 引數是一個字串。 $timestamp 指定 Unix 時間戳,可選,date() 函式返回一個字串。
我們可以在 date() 函式中指定各種格式來根據我們的需要返回日期。我們可以使用這種格式返回一年中的當前月份。
有一個由 DateTimeInterface::format() 指定的格式字元列表來設定日期。讓我們探索一些返回當前月份的格式字元。
F:返回當前月份的文字表示。例如,一月。m:它返回當前月份的數字表示,帶有字首0。例如,01。M:返回當前月份的簡短文字表示。例如,Jan。n:它返回當前月份的數字表示,不帶字首0。例如,1。
我們現在將實現以下格式字元來返回當前月份。
例如,編寫 date() 函式並使用上述格式字元作為函式的引數。
不要忘記用引號包裹格式字元並使用 echo 語句來列印函式。
一年中的當前月份是二月,我們可以看到當前月份顯示在下面的輸出部分中。這樣,我們就可以在 PHP 中使用格式字元來獲取當前月份。
示例程式碼:
echo date('m');
echo ": Using the `m` format"."";
echo date('F');
echo ": Using the `F` format"."";
echo date('M');
echo ": Using the `M` format"."";
echo date('n');
echo ": Using the `n` format"."";
?>
輸出:
02: Using the `m` format
February: Using the `F` format
Feb: Using the `M` format
2: Using the `n` format
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Subodh Poudel
Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.
LinkedIn