如何在 PHP 中获取当前年份

Minahil Noor 2023年1月30日 PHP PHP DateTime
  1. 使用 date() 函数获取 PHP 的当前年份
  2. 使用 strftime() 函数获取 PHP 的当前年份
  3. 使用 DateTime 对象获取 PHP 的当前年份
如何在 PHP 中获取当前年份

在本文中,我们将介绍获取当前年份的方法。

  • 使用 date() 函数
  • 使用 strftime() 函数
  • DateTime 对象中使用 format() 方法

使用 date() 函数获取 PHP 的当前年份

我们可以使用内置的 date() 函数来获取当前年份。它以指定的格式返回当前日期。其语法如下

date($format, $timestamp);

参数 $format 说明将要显示的最终日期格式。它有多种变体。它应是一个字符串形式。

参数 $timestamp 是可选的。它告知特定的时间戳,并相应显示日期。如果没有传递时间戳,则默认使用当前日期。

<?php
$Date = date("d-m-Y");  
echo "The current date is $Date.";
echo "\n";
$Year = date("Y");
echo "The current year is $Year.";
echo "\n";
$Year2 = date("y");
echo "The current year in two digits is $Year2.";
?>

格式 "d-m-Y" 将返回带有 4 位数字年份值的完整日期。格式 "Y" 将返回 4 位数字的年份值。格式 "y" 将返回 2 位数的年份值。你可以根据需要进行修改。

输出:

The current date is 20-04-2020.
The current year is 2020.
The current year in two digits is 20.

使用 strftime() 函数获取 PHP 的当前年份

PHP 中的另一个内置函数-strftime() 也可以返回给定格式的日期或时间字符串。对于日期和时间的变化,它具有不同的格式。

strftime($format, $timestamp);

参数 $format 说明日期或时间的格式。它是一个字符串。

$timestamp 是一个可选变量,用于告知 UNIX 时间戳记。它是整数。如果未给出,该函数将返回当前日期或时间。

<?php
$Date = strftime("%d-%m-%Y");  
echo "The current date is $Date.";
echo "\n";
$Year = strftime("%Y"); 
echo "The current year is $Year.";
echo "\n";
$Year2 = strftime("%y"); 
echo "The current year in two digits is $Year2.";
?>
警告

我们可以使用格式 "%Y" 获得当前年份的 4 位数字,使用格式 "%y" 获得 2 位数字的当前年。

输出:

The current date is 20-04-2020.
The current year is 2020.
The current year in two digits is 20.

使用 DateTime 对象获取 PHP 的当前年份

在 PHP 中,DateTimeformat() 函数用于以指定的格式显示日期。

$ObjectName = new DateTime();
$ObjectName->format($format); 

参数 $format 指定日期的格式。

<?php
$Object = new DateTime();  
$Date = $Object->format("d-m-Y");  
echo "The current date is $Date.";
echo "\n";
$Year = $Object->format("Y"); 
echo "The current year is $Year.";
echo "\n";
$Year2 = $Object->format("y"); 
echo "The current year in two digits is $Year2.";
?>

输出是具有指定格式的日期。

输出:

The current date is 20-04-2020.
The current year is 2020.
The current year in two digits is 20.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

相关文章 - PHP DateTime