PHP函数——strtotime的用法和示例
PHP函数strtotime是一个非常有用的函数,用于将人类可读的日期时间格式转换为Unix时间戳。它的语法非常简单,只有一个参数:
int strtotime ( string $time [, int $now = time() ] )
其中,$time参数是要转换的日期时间字符串,支持各种格式;$now参数是可选的,表示参照时间,默认为当前时间。函数返回值是一个整数,表示Unix时间戳。
strtotime函数支持的日期时间字符串格式有很多,以下是一些常用的示例:
1. "now":表示当前时间的字符串,可以理解为time()的字符串表示;
echo strtotime("now"); // 输出当前时间的Unix时间戳
2. "+1 day":"day"可以是"minute"、"hour"、"day"、"week"、"month"、"year",表示在当前时间基础上增加1天、1分钟、1小时等;
echo strtotime("+1 day"); // 输出当前时间加上1天的Unix时间戳
3. "yesterday":"yesterday"表示昨天的时间
echo strtotime("yesterday"); // 输出昨天的Unix时间戳
4. "next Monday":"next"可以是"last"、"next"、"this",表示下周一、上周一、这周一的时间;
echo strtotime("next Monday"); // 输出下周一的Unix时间戳
5. "11 September 2001":具体日期的字符串,支持多种格式,如"Y-m-d"、"m/d/Y"、"F jS, Y"等;
echo strtotime("11 September 2001"); // 输出指定日期的Unix时间戳
6. "2019-04-15 12:00:00":指定日期时间的字符串,可以精确到秒;
echo strtotime("2019-04-15 12:00:00"); // 输出指定日期时间的Unix时间戳
strtotime函数还支持一些其他格式,如"-1 week 2 days 4 hours 2 seconds"表示当前时间减去一周两天四小时两秒。
除了上述示例,strtotime还支持特殊的日期格式,如"tomorrow"表示明天的时间,"first day of next month"表示下个月的 天等。
需要注意的是,strtotime函数在处理日期时间字符串时,会尝试使用当前时区来解析,因此在使用前应该先设置好时区。
总的来说,strtotime函数是PHP中非常方便的一个日期时间处理函数,可以将不同格式的日期时间字符串转换为Unix时间戳,方便进行日期时间的计算和比较。
