欢迎访问宙启技术站
智能推送

使用PHP函数将日期和时间转换为时间戳

发布时间:2023-07-06 04:37:50

在PHP中,可以使用strtotime()函数将日期和时间转换为时间戳。这个函数用于将任何英文文本日期字符串解析为Unix时间戳。Unix时间戳是自1970年1月1日以来经过的秒数。

strtotime()函数的语法如下:

strtotime(string $time, int $now = time()): int|false

其中,$time参数指定要转换的日期和时间字符串。$now参数是可选的,用于指定当前时间的时间戳。如果未提供此参数,默认使用当前时间的时间戳。

strtotime()函数返回一个整数(Unix时间戳)或者false,表示转换失败。

下面是一些使用strtotime()函数将日期和时间转换为时间戳的示例:

$time1 = "2021-01-01 00:00:00";
$timestamp1 = strtotime($time1);
echo "Timestamp for {$time1} is {$timestamp1}" . PHP_EOL;

$time2 = "2022-12-31 23:59:59";
$timestamp2 = strtotime($time2);
echo "Timestamp for {$time2} is {$timestamp2}" . PHP_EOL;

$currentDate = date("Y-m-d");
$currentTime = "12:00:00";
$datetime = $currentDate . " " . $currentTime;
$timestamp3 = strtotime($datetime);
echo "Timestamp for {$datetime} is {$timestamp3}" . PHP_EOL;

输出:

Timestamp for 2021-01-01 00:00:00 is 1609455600
Timestamp for 2022-12-31 23:59:59 is 1672531199
Timestamp for 2022-12-31 12:00:00 is 1672492800

在示例中,我们使用了不同的日期和时间字符串,并通过strtotime()函数将它们转换为时间戳。每个示例的输出显示了对应的时间戳。

要注意的是,strtotime()函数可以处理多种日期和时间格式。例如,它可以解析英文日期、带时区的日期、相对日期(如“+1 week”表示当前日期加一周)等。

但是值得注意的是,strtotime()函数在解析一些特殊日期格式时可能会出现一些问题,因此在使用时需谨慎。如果遇到无法解析的日期格式,strtotime()函数可能会返回false,因此在使用转换后的时间戳前应该首先检查返回值。

综上所述,PHP的strtotime()函数可以方便地将日期和时间字符串转换为时间戳。