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

PHP中的strtotime函数用法及其常见应用

发布时间:2023-06-10 20:24:23

PHP中的strtotime()函数用于将日期时间格式的字符串转换为时间戳。通过这个函数,我们可以将不同格式的时间字符串转化为时间戳,从而进行日期时间的计算和比较。本文将详细介绍strtotime函数的用法和常见应用。

一、strtotime()函数的语法

strtotime()函数的语法如下:

strtotime(timeString, [nowTime])

其中,timeString是日期时间格式的字符串,必选参数;nowTime是可选参数,表示当前时间的时间戳,默认是当前系统时间。这个参数可以是时间戳格式或日期时间字符串格式。

例如:

$time = strtotime('2018-06-30 12:00:00');

表示将时间字符串 '2018-06-30 12:00:00' 转化成时间戳格式,存入变量 $time 中。

二、strtotime()函数常见格式

strtotime()函数支持的时间格式非常多,下面列举一些常见的时间格式。

1. 短日期格式

格式是 yyyy-mm-dd 或者 yyyy/mm/dd。例如:

strtotime('2020-10-01'); 

strtotime('2020/10/01');

2. 长日期格式

格式是 yyyy-mm-dd hh:mm:ss 或 yyyy-mm-dd hh:mm:ss AM/PM。例如:

strtotime('2020-10-01 12:30:45'); 

strtotime('2020-10-01 12:30:45 PM');

3. 相对日期格式

相对日期格式是一种比较灵活的日期格式,它可以表示一些相对时间,比如“5 days ago ”表示5天前,“next Monday”表示下个星期一等。例如:

strtotime('5 days ago'); 

strtotime('next Monday');

4. 时间戳格式

时间戳格式是以秒为单位表示的时间,是一种比较方便的时间格式。例如:

strtotime('1603259800');

三、strtotime()函数的常见应用

1. 获取当前时间戳

利用strtotime()函数可以获取当前时间的时间戳。例如:

echo strtotime('now');

2. 格式化输入日期

如果输入的日期格式不一致,可以使用strtotime()函数将其转化为一致的格式。例如:

echo strtotime('2020/10/01'); 

3. 计算相对时间

利用strtotime()函数,可以进行相对时间的计算。例如:

//计算十天后的时间戳

echo strtotime('+10 day'); 

//计算两小时后的时间戳

echo strtotime('+2 hour'); 

4. 比较两个时间

利用strtotime()函数,可以将时间字符串转化为时间戳,然后进行比较。例如:

//比较两个时间

$time1 = strtotime('2020-10-01 17:30:00');

$time2 = strtotime('2020-10-01 17:00:00');

if ($time1 > $time2) {

    echo '时间1比时间2晚';

} else {

    echo '时间2比时间1晚';

}

5. 将时间字符串转化为指定格式

利用strtotime()函数,可以将时间字符串按照指定格式转化为另外一种时间格式。例如:

//将 2020-10-01 转化为 10/01/20 格式的日期

echo date('m/d/y', strtotime('2020-10-01'));

四、strtotime()函数的注意事项

1. 输入日期字符串必须是合法的日期格式,否则会返回false。

2. 输入日期字符串如果没有时分秒,则默认时分秒为00:00:00。

3. 输入日期字符串如果包含时分秒,则时间格式必须为hh:mm:ss或者hh:mm:ss AM/PM,否则也会返回false。

4. 在相对日期格式中,关键字不区分大小写。例如 “next Monday” 可以写成 “nExT MoNDaY”。