PHPstrtotime()函数:如何使用strtotime()函数将日期字符串转换为时间戳
PHP的strtotime()函数可以将日期字符串转换为时间戳。时间戳是一种特殊的表示时间的整数,它表示从1970年1月1日0时0分0秒(格林威治时间)起到指定时间的秒数。在PHP中,常用时间戳来进行时间的计算和比较。
strtotime()函数的语法格式如下:
strtotime(string $time [, int $now = time()])
其中,$time是需要转换成时间戳的日期字符串,$now是可选参数,表示当前的时间戳,如果不传入此参数,则默认使用当前的时间戳。
strtotime()函数支持的日期字符串格式非常多,下面介绍几个常见的格式:
1. 普通日期格式
例如:"2019-09-26"、"2022/01/20"等。
示例代码:
$timestamp = strtotime("2019-09-26");
echo $timestamp; // 输出:1569436800
2. 中文日期格式
例如:"2022年1月20日"、"2022-01-20 星期四"等。
示例代码:
$timestamp = strtotime("2022年1月20日");
echo $timestamp; // 输出:1642598400
3. 相对时间格式
例如:"now"、"tomorrow"、"+1 day"等。
示例代码:
$timestamp = strtotime("now");
echo $timestamp; // 输出:1638968734
$timestamp = strtotime("tomorrow");
echo $timestamp; // 输出:1639055134
$timestamp = strtotime("+1 day");
echo $timestamp; // 输出:1639055189
4. 英文时间格式
例如:"Monday next week"、"2 weeks ago"等。
示例代码:
$timestamp = strtotime("Monday next week");
echo $timestamp; // 输出:1640908800
$timestamp = strtotime("2 weeks ago");
echo $timestamp; // 输出:1637160789
注意:strtotime()函数对于错误的日期字符串会返回false,因此在使用此函数时需要注意日期格式的正确性。
除了strtotime()函数,PHP还提供了其他几个类似的函数用于时间戳和日期字符串的转换,例如:
1. date()函数:将时间戳格式化为日期字符串。
2. mktime()函数:将日期时间转换为时间戳。
3. strftime()函数:用于格式化本地时间/日期,可以根据本地的语言环境输出。
通过这些函数,可以方便地进行时间戳和日期字符串之间的转换,从而轻松实现各种时间操作和计算。
