如何在 PHP 中将日期转换为时间戳

在本文中,我们将介绍在 PHP 中将 date 转换为 timestamp 的方法。

  • 使用 strtotime() 函数
  • 使用 strptime() 函数
  • 使用 getTimestamp() 函数
  • 使用 format() 函数

使用 strtotime() 函数将日期转换为 PHP 中的时间戳

内置函数 strtotime() 将日期转换为 Unix 时间戳。Unix 时间戳是从 Unix 时代(1970 年 1 月 1 日)计算出的总秒数。使用此函数的正确语法如下

strtotime($dateString,$timeNow);

此函数有两个参数。$dateString 是应该符合 PHP 有效格式的日期/时间字符串。它是必填参数。另一个参数 $timeNow 是可选的,它是用于计算相对日期的时间戳。如果省略第二个参数,则当前时间 now 是默认值。

<?php
$timestamp = strtotime("23-04-2020");
echo "The timestamp is $timestamp.";
?>

这里的日期格式为 "d-m-Y"。我们仅传递了一个参数,因为它将把 date 转换为 Unix 时间戳。

输出:

The timestamp is 1587600000.

使用 strptime() 函数将日期转换为 PHP 中的时间戳

这是将日期转换为 Unix 时间戳的另一个功能。它不会将日期直接转换为时间戳。它返回一个数组,该数组讲述秒,分钟,小时以及其他一些详细信息。我们可以使用这些详细信息将日期转换为时间戳。

strptime($dateString, $format);

它有两个必填参数。$dateString 是日期字符串,$format 是解析 $dateString 的格式。

<?php
$array = strptime('23-04-2020', '%d-%m-%Y');
$timestamp = mktime(0, 0, 0, $array['tm_mon']+1, $array['tm_mday'], $array['tm_year']+1900);
echo "The timestamp is $timestamp.";
?>

输出:

The timestamp is 1587600000.

生成数组后,mktime() 函数将 date 转换为 timestamp。

mktime() 函数的语法是

mktime(hour, minute, second, month, day, year, is_dst)

is_dst 指定日期时间是否为夏令时,但已从 PHP 7.0.0 中删除。

警告
我们应该在 $array['tm_mon'] 上加 1,然后将和用作 mktime 中的 month 的参数,因为 $array['tm_mon'] 从’0’开始,或者换句话说,一月份的 $array['tm_mon'] 为 0。

使用 getTimestamp() 函数将日期转换为 PHP 中的时间戳

DateTime 对象的 getTimestamp()方法是一种将日期转换为时间戳的简单方法。它有另一种表示方法 date_timestamp_get(),它是程序样式表示。

$datetimeObject->getTimestamp();

我们将创建一个 Datetime 对象来调用此函数。这是调用函数的面向对象风格。

<?php
$date = new DateTime('2020-04-23');
$timestamp = $date->getTimestamp();
echo "The timestamp is $timestamp.";
?>

Datetime 类的对象 $date 已调用方法 getTimestamp()将 date 转换为 Unix timestamp。

输出:

The timestamp is 1587600000.

使用 format() 函数将日期转换为 PHP 中的时间戳

我们还可以使用 DateTime 的 format()方法将 date 转换为 timestamp。该方法还有另一种表示形式 date_format(),它是 format()函数的过程样式表示。

$datetimeObject->format("U");

为了将 date 转换为 timestamp,我们将作为字符串传递的格式为 "U"

<?php
$dateObject = new DateTime('2020-04-23');
$timestamp = $dateObject->format("U");
echo "The timestamp is $timestamp.";
?>

Datetime 类的对象 $dateObject 调用了函数 format() 将日期转换为 Unix 时间戳。

输出:

The timestamp is 1587600000.