使用PHP中的strtotime函数将日期和时间字符串转换为时间戳
PHP中的strtotime函数是一个非常有用的函数,它可以将日期和时间字符串转换为时间戳。它可以将几乎所有日期和时间字符串转换为时间戳,例如:
strtotime("now"); // 当前时间的时间戳
strtotime("10 September 2000"); // 2000年9月10日的时间戳
strtotime("+1 day"); // 明天的时间戳
strtotime("+1 week"); // 下周的时间戳
strtotime("+1 week 2 days 4 hours 2 seconds"); // 下周的某一天的时间戳
strtotime()函数接收一个日期和时间的字符串,并将其转换为时间戳。 如果字符串不是合法的日期或时间格式,strtotime()函数将返回FALSE。
让我们来看看如何使用strtotime()函数来将日期和时间字符串转换为时间戳。
## 1. 将当前时间转换为时间戳
要将当前时间转换为时间戳,可以使用"now"字符串作为参数传递给strtotime()函数。例如:
$timestamp = strtotime("now");
echo $timestamp;
以上代码将输出当前时间的时间戳。
## 2. 将日期字符串转换为时间戳
要将日期字符串转换为时间戳,可以使用"YYYY-MM-DD"格式的日期字符串作为strtotime()函数的参数。例如:
$date = "2021-01-01"; $timestamp = strtotime($date); echo $timestamp;
以上代码将输出2021-01-01的时间戳。
## 3. 将时间字符串转换为时间戳
要将时间字符串转换为时间戳,可以使用"HH:MM:SS"格式的时间字符串作为参数传递给strtotime()函数。例如:
$time = "12:30:00"; $timestamp = strtotime($time); echo $timestamp;
以上代码将输出12:30:00的时间戳。
## 4. 将日期和时间字符串转换为时间戳
要将日期和时间字符串转换为时间戳,可以使用"YYYY-MM-DD HH:MM:SS"格式的日期和时间字符串作为参数传递给strtotime()函数。例如:
$datetime = "2021-01-01 12:30:00"; $timestamp = strtotime($datetime); echo $timestamp;
以上代码将输出2021-01-01 12:30:00的时间戳。
## 5. 使用相对时间字符串转换为时间戳
strtotime()函数也支持相对时间字符串,例如"next week", "yesterday", "2 days ago"等。相对时间字符串的格式非常灵活,可以指定一个或多个时间单位,例如:
$timestamp = strtotime("+1 week");
echo $timestamp;
$timestamp = strtotime("+2 days");
echo $timestamp;
$timestamp = strtotime("+3 hours");
echo $timestamp;
以上代码将分别输出下周、两天后和三小时后的时间戳。
相对时间字符串也可以组合使用,例如:
$timestamp = strtotime("+1 week 2 days 4 hours 2 seconds");
echo $timestamp;
以上代码将输出一周后的某一天的时间戳。
不过需要注意,相对时间字符串必须放在日期或时间字符串之后,例如:
$timestamp = strtotime("2021-01-01 +1 week 2 days");
echo $timestamp;
以上代码将输出2021-01-01之后一周两天的时间戳。
## 总结
在PHP中,使用strtotime()函数可以将日期和时间字符串转换为时间戳。我们可以通过传递不同的字符串参数来获取不同的时间戳。使用strtotime()函数非常方便,不需要记住时间戳的格式,可以直接使用符合我们通常使用习惯的日期和时间字符串来处理时间戳。
