如何在 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