一、時間戳轉(zhuǎn)換為日期時間
在 PHP 中,UNIX 時間戳可以被轉(zhuǎn)化為日期時間字符串,這是通過調(diào)用 date() 函數(shù)實現(xiàn)的。在 ThinkPHP5.1 中,我們可以使用 \think\helper\Str 類的 toDateTimeString() 方法來將時間戳轉(zhuǎn)換為日期時間字符串。
例如:
use think\helper\Str; $time = 1573679399; echo Str::toDateTimeString($time); // 輸出: 2019-11-14 14:03:19
登錄后復制
二、日期時間轉(zhuǎn)換為時間戳
在 PHP 中,我們可以使用 strtotime() 函數(shù)將日期時間字符串轉(zhuǎn)換為 UNIX 時間戳。在 ThinkPHP5.1 中,我們可以使用 \think\helper\Str 類的 unixTime() 方法來將日期時間字符串轉(zhuǎn)換為時間戳。
例如:
use think\helper\Str; $datetime = '2019-11-14 14:03:19'; echo Str::unixTime($datetime); // 輸出: 1573679399
登錄后復制
三、時間格式化
在 PHP 中,我們可以使用 date() 函數(shù)對日期時間字符串進行格式化。在 ThinkPHP5.1 中,我們可以使用 \think\helper\Str 類的 dateFormat() 方法對日期時間字符串進行格式化。
例如:
use think\helper\Str; $datetime = '2019-11-14 14:03:19'; echo Str::dateFormat($datetime, 'Y年m月d日 H:i:s'); // 輸出: 2019年11月14日 14:03:19
登錄后復制
在 dateFormat() 方法中,第一個參數(shù)是需要格式化的日期時間字符串,第二個參數(shù)是格式化字符串。常用的格式化字符串如下:
| 日期格式字符 | 說明 |
|---|---|
| Y | 年份(4 位數(shù)) |
| m | 月份(01-12) |
| d | 日期(01-31) |
| H | 小時(00-23) |
| i | 分鐘(00-59) |
| s | 秒鐘(00-59) |
四、時間差計算
在 PHP 中,我們可以使用 strtotime() 函數(shù)計算兩個日期時間之間的時間差。在 ThinkPHP5.1 中,我們可以使用 \think\helper\Str 類的 time() 方法計算兩個日期時間之間的時間差。
例如:
use think\helper\Str;
$start = '2019-11-14 14:03:19';
$end = '2019-11-15 16:05:12';
$diff = Str::time($start, $end);
echo $diff->format('%a 天 %h 小時 %i 分鐘 %s 秒');
// 輸出: 1 天 2 小時 1 分鐘 53 秒
登錄后復制
在 time() 方法中,第一個參數(shù)是開始時間,第二個參數(shù)是結(jié)束時間。如果要計算兩個時間之間的天數(shù)、小時數(shù)、分鐘數(shù)、秒數(shù)等等,可以使用 DateTime 對象的 format() 方法。
以上就是ThinkPHP5.1中如何使用時間處理函數(shù)的詳細內(nèi)容,更多請關注www.xfxf.net其它相關文章!






