Laravel項目開發的時候,經常遇到計算兩個時間相差的天數、相差小時數、相差秒數等需求
一個星期開始和結束的日期
Carbon::now()->startOfWeek()->toDateString(); //一個星期開始的日期
Carbon::now()->endOfWeek()->toDateString(); //一個星期結束的日期
Carbon::now()->daysInMonth; //這個月有多少天
Carbon::now()->day; //當前的日 eg:17
1.計算時間天數差
carbon::parse ('2020-12-10')->diffInDays('2020-12-28', false); //為正負數
carbon::parse ('2020-12-10')->diffInDays('2020-12-28', true);//為正負數的絕對值
2.計算相差小時數、相差秒數等
$date = '2020-12-11 12:59:59';
$carbon = carbon::parse ($date); // 格式化一個時間日期字符串為 carbon 對象
$int = (new Carbon)->diffInSeconds ($carbon, false); // $int 為正負數
or $int = (new Carbon)->diffInSeconds ($carbon, true); // $int 為正負數的絕對值
類似還有:
$int = (new Carbon)->diffInMinutes($carbon, true);
$int = (new Carbon)->diffInHours($carbon, true);
等等,可計算當前時間與給定的時間差。
時間格式化的方式
使用 parse 方法解析任何順序和類型的日期(結果為 Carbon 類型的日期時間對象)
和php
中的date
函數用戶基本相同
Carbon::parse($this->kssj)->format("F");
格式化方式 | 說明 |
---|---|
Y | 4位數字年,y為2位數字,如99即1999年 |
m | 數字月份,前面有前導0,如01。n 為無前導0數字月份 |
F | 月份,完整的文本格式,例如 January 或者 March |
M | 三個字母縮寫表示的月份,例如 Jan 或者 Mar |
D | 星期幾,三個英文字母; 如: "Fri |
d | 月份中的第幾天,前面有前導0,如03。j 為無前導0的天數 |
w | 星期中的第幾天,以數字表示,0表示星期天 |
z | 年份中的第幾天,范圍0-366 |
W | 年份中的第幾周,如第32周 |
H | 24小時格式,有前導0,h為12小時格式 |
G | 24小時格式,無前導0,g為對應12小時格式 |
i | 分鍾格式,有前導0 |
s | 秒格式,有前導0 |
A | 大寫上下午,如AM,a為小寫 |