在 PHP 中获取日期的当前月份

Roshan Parmar 2023年1月30日
  1. 在 PHP 中使用 date() 函数获取日期的当前月份
  2. 在 PHP 中使用 strtotime()date() 函数获取日期的当前月份
  3. 使用 PHP 中的 DateTime 类获取当前月份
在 PHP 中获取日期的当前月份

date() 函数是一个内置的 PHP 函数,用于格式化时间戳。在 UNIX Timestamp 中,计算机保存日期和时间。自 1970 年 1 月 1 日起,此时间以秒为单位。由于这对于人类来说难以理解,PHP 将时间戳更改为更清晰易懂的格式。

有几种方法可以在 PHP 中获取日期的月份部分。在以下部分中,你将学习如何从当前日期或任何日期获取日期的月份。

在 PHP 中使用 date() 函数获取日期的当前月份

PHP 的 date() 函数可以根据其第一个参数中的格式化字符为你提供与日期和时间相关的信息。最多可以向函数发送两个参数。如果你只使用一个参数,它将返回有关当前时间的信息。

要生成一个月的三种不同形式,请在 date() 函数的第一个参数中使用三种不同的格式字符。这些是格式化字符:

date() 函数具有以下格式选项: date() 函数的格式参数是一个可以包含多个字符的字符串,允许你以多种形式生成日期,如下所示:

<?php
echo "Current month representation, having leading zero in 2 digit is: " . date("m");
echo "\n";
echo "The Syntex representation of current month with leading zero is: " . date("M");
echo "\n";
echo "Current month representation,not having leading zero in 2 digit is: " . date("n");
?>

输出:

Current month representation, having leading zero in 2 digits is: 12
The Syntex representation of the current month with leading zero is: Dec
Current month representation, not having leading zero in 2 digits is: 12

这里,

d – 代表月份的日期。使用两个带前导零的数字(01 或 31)。
D - 在文本中,代表星期几(MonSun)。
m - 月份由带前导零的数字字母 m 表示(01 或 12)。
M - 在文本中,M 代表月份并被缩短(JanDec)。
y – 表示两位数的年份(07 或 21)。
Y - 四个数字中的年份由字母 Y 表示。

在 PHP 中使用 strtotime()date() 函数获取日期的当前月份

我们将通过两个步骤使用 strtotime() 方法从任何日期获取月份。

首先,将日期转换为其时间戳相等。使用带有格式化字符的 date() 函数从该时间戳中获取月份。

<?php
$timestamp = strtotime("5th September 2003");
echo "Current month representation, having leading zero in 2 digits is: " . date("m", $timestamp);
echo "\n";
echo "The Syntex representation of current month with leading zero is: " . date("M", $timestamp);
echo "\n";
echo "Current month representation,not having leading zero in 2 digits is: " . date("n", $timestamp);
?>

输出:

Current month representation, having leading zero in 2 digits is: 09
The Syntex representation of the current month with leading zero is: Sep
Current month representation,not having leading zero in 2 digits is: 9

使用 PHP 中的 DateTime 类获取当前月份

PHP 5.2 引入了某些预先构建的类来帮助开发人员解决常见问题。DateTime 是类之一,它处理日期和时间问题。按照以下两个步骤使用 DateTime 类检索当前月份:

首先,创建一个 DateTime() 类对象。当前时间在使用 DateTime() 类时表示,不带任何参数。

然后,使用 DateTime() 类的 format() 函数从新形成的对象中获取年份。

<?php
$now = new DateTime();
echo "Current month representation, having leading zero in 2 digit is: " . $now->format('m');
echo "\n";
echo "The Syntex representation of current month with leading zero is: " . $now->format('M');
echo "\n";
echo "Current month representation,not having leading zero in 2 digit is: " . $now->format('n');
?>

输出:

The 2 digit representation of the current month with leading zero is: 12
The textual representation of the current month with leading zero is: Dec
The 2 digit representation of the current month without leading zero is: 12

相关文章 - PHP DateTime