如何在 PHP 中将一种日期格式转换为另一种日期格式

Minahil Noor 2023年1月30日
  1. 在 PHP 中使用 date()strtotime() 函数将一种日期格式转换为另一种日期格式
  2. 在 PHP 中使用 createFromFormat()format() 函数将一种日期格式转换为另一种日期格式
如何在 PHP 中将一种日期格式转换为另一种日期格式

在本文中,我们将介绍在 PHP 中将一种日期格式转换为另一种格式的方法。

  • 使用 date()strtotime() 函数
  • 使用 createFromFormat()format() 函数

在 PHP 中使用 date()strtotime() 函数将一种日期格式转换为另一种日期格式

date() 函数将时间戳转换为日期 date。使用此函数的正确语法如下

date( $format, $timestamp);

$format 是转换日期的特定格式。

$timestamp 是一个可选参数。它根据传递的时间戳给出日期。如果省略的话,那么我们将获得当前的日期。

函数 strtotime() 是 PHP 中的内置函数。此函数将日期转换为时间。使用此函数的正确语法如下。

strtotime($dateString, $timeNow);

$dateString 是必需参数,它是日期的字符串表示形式。

$timeNow 是一个可选参数。它是用于计算相对日期的时间戳。

<?php
$originalDate = "2020-04-29";
//original date is in format YYYY-mm-dd
$timestamp = strtotime($originalDate); 
$newDate = date("m-d-Y", $timestamp );
echo "The new date is $newDate.";
?>

我们使用了 date()strtotime() 函数将一种日期格式转换为另一种格式。函数 strtotime() 已将原始日期转换为时间戳。然后使用 date() 函数将该时间戳转换为所需格式的日期。

输出:

The new date is 04-29-2020.

在 PHP 中使用 createFromFormat()format() 函数将一种日期格式转换为另一种日期格式

函数 createFromFormat() 是 PHP 中的内置函数。该函数将时间戳或日期字符串转换为 DateTime 对象。使用此函数的正确语法如下。

DateTime::createFromFormat($format, $time, $timezone);

变量 $format 是日期的格式,$time 是时间或字符串中的日期,$timezone 是时区。前两个参数是必需参数。

format() 函数用于将 date 格式化为所需格式。使用此函数的正确语法是

$datetimeObject->format($formatString); 

参数 $formatString 指定所需的格式。

<?php
$originalDate = "2020-04-29";
//original date is in format YYYY-mm-dd
$DateTime = DateTime::createFromFormat('Y-m-d', $originalDate);
$newDate = $DateTime->format('m-d-Y');
echo "The new date is $newDate.";
?>

在这里,我们使用 createFromFormat() 函数创建了一个 DateTime 对象。然后,DateTime 对象调用 format() 函数将一种日期格式转换为另一种。

输出:

The new date is 04-29-2020.

相关文章 - PHP Date