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

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

发布时间:2023-06-18 00:16:14

在PHP中,strtotime()函数可用于将日期和时间转换为Unix时间戳。Unix时间戳表示从1970年1月1日00:00:00 UTC至指定时间的秒数。以下是如何使用strtotime()函数进行转换的示例:

1. 将当前日期和时间转换为Unix时间戳:

$current_time = strtotime('now');
echo $current_time;

输出:当前日期和时间的Unix时间戳

2. 将指定日期和时间转换为Unix时间戳:

$date_time = '2021-01-01 12:00:00';
$unix_time = strtotime($date_time);
echo $unix_time;

输出:指定日期和时间的Unix时间戳

3. 支持多种日期和时间格式:

$date1 = 'tomorrow';
$date2 = 'next week';
$date3 = 'last day of next month';

$unix_time1 = strtotime($date1);
$unix_time2 = strtotime($date2);
$unix_time3 = strtotime($date3);

echo $unix_time1;
echo $unix_time2;
echo $unix_time3;

输出:明天、下周、下个月的最后一天的Unix时间戳

4. 可以在日期和时间字符串中添加和减去时间单位:

$date_time1 = '2021-01-01 +1 day';
$date_time2 = '2021-01-01 -1 week';
$date_time3 = '2021-01-01 +1 month';

$unix_time1 = strtotime($date_time1);
$unix_time2 = strtotime($date_time2);
$unix_time3 = strtotime($date_time3);

echo $unix_time1;
echo $unix_time2;
echo $unix_time3;

输出:2021年1月2日、2020年12月25日、2021年2月1日的Unix时间戳

需要注意的是,strtotime()函数会自动尝试识别输入字符串的格式。如果输入字符串无法转换为日期和时间,则会返回FALSE。在使用strtotime()函数之前,建议对输入字符串进行验证。