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

PHP中的时间函数使用技巧

发布时间:2023-06-19 09:37:19

PHP中有很多可以用来处理时间的函数,例如date()、time()、strtotime()以及strtotime()。速成课中将为大家介绍这些函数以及它们的常见用法和技巧。

一、date()函数

date()函数用于格式化日期的输出,它的语法为:

string date ( string $format [, int $timestamp = time() ] )

其中,$format参数指定输出的日期时间格式,示例:

echo date('Y-m-d H:i:s');          // 2022-02-22 16:45:30
echo date('l jS F Y h:i:s A');     // Tuesday 22nd February 2022 04:45:30 PM

$timestamp参数表示要格式化的时间戳,默认为当前时间戳。

二、time()函数

time()函数用于获取当前时间戳,它的语法为:

int time ( void )

示例如下:

echo time();       // 1645501530

三、strtotime()函数

strtotime()函数用于将字符串时间转换成时间戳,它的语法为:

int strtotime ( string $time [, int $now = time() ] )

示例如下:

echo strtotime('2022-02-22 16:45:30');    // 1645501530

$now参数可选,表示当前时间戳,默认为当前时间戳。

四、strtotime()函数进阶

strtotime()函数在处理字符串时,还支持一些特定格式和语法,下面列举几个常用的:

1. 明天、后天、下周等语法:

echo strtotime('tomorrow');       // 下一个零点的时间戳
echo strtotime('next Monday');    // 下一个星期一零点的时间戳

2. "-"/"+"操作符:

echo strtotime('+3 day');         // 三天后零点的时间戳
echo strtotime('next Wednesday +1 week');   // 下个星期三加一周时间的时间戳

3. 相对日期格式:

echo strtotime('March 1 2022');   // 1646077200
echo strtotime('1 March 2022');   // 1646077200
echo strtotime('first day of March 2022'); // 1646077200
echo strtotime('last day of February 2022'); // 1646110799

五、时间戳加减

PHP中可以通过对时间戳加减来进行时间的计算,示例如下:

echo time() - 60;             // 当前时间的前一分钟时间戳
echo time() + 3600;           // 当前时间的后一小时时间戳
echo time() - 86400;          // 当前时间的前一天时间戳

六、时区设置

PHP中可以通过date_default_timezone_set()函数来设置时区,示例如下:

date_default_timezone_set('Asia/Shanghai');

七、本地化时间

PHP中使用setlocale()函数可以设置本地化时间,示例如下:

setlocale(LC_TIME, 'zh_CN.utf8');
echo strftime('%Y-%m-%d %H:%M:%S', time());   // 2022-02-22 16:45:30
echo strftime('%A, %d %B %Y %H:%M:%S', time()); // 星期二, 22 二月 2022 16:45:30

以上就是关于PHP中时间函数的使用技巧的介绍,希望对大家有所帮助。