PHP 日期时间类 Carbon 的常见用法

Carbon 继承了 PHP DateTime 类,所以 DateTime 类的方法同样适用于 Carbon 类。

初始化一个日期

use Carbon\Carbon;

$today = new Carbon('2018-08-01');

本月第一天,上月第一天

$first_day = new Carbon('first day of this month');
$first_day = new Carbon('first day of last month');
return $month->format('Y-m');   // 2018-08

今日日期

echo Carbon::today()->toDateString();       // 2018-09-10

当前时间

Carbon::now();             // 2018-10-08 14:24:15.074542 Asia/Shanghai (+08:00)
echo Carbon::now();    // 2018-10-08 14:28:10

时间差

$start  = new Carbon('2018-10-04 15:00:03');
$end    = new Carbon('2018-10-05 17:00:09');
$start->diff($end)->format('%H:%I:%S');

02:00:06

参考

https://carbon.nesbot.com/docs/