企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] > [github](https://github.com/briannesbitt/Carbon) ## 安装 ``` $ composer req nesbot/carbon ``` ## 示例 ### 获取某天 ``` require __DIR__ . '/vendor/autoload.php'; use Carbon\Carbon; $now = Carbon::now(); echo "$now\n"; // 2020-08-31 15:06:36 $today = Carbon::today(); echo "$today\n"; // 2020-08-31 00:00:00 $yes = Carbon::yesterday(); echo "Yesterday: $yes\n"; // 2020-08-30 00:00:00 $tom = Carbon::tomorrow(); echo "Tomorrow: $tom\n"; // 2020-09-01 00:00:00 ``` ### 一周中给定日期的下一个/上一个出现 ``` require __DIR__ . './../vendor/autoload.php'; use Carbon\Carbon; $now = Carbon::now(); echo "$now\n"; // 2020-08-31 15:12:51 $next_monday = $now->next(Carbon::MONDAY); echo "$next_monday\n"; // 2020-09-07 00:00:00 $prev_monday = $now->previous(Carbon::MONDAY); echo "$prev_monday\n"; // 2020-08-31 00:00:00 ``` ### 日期时间包括年,月,日或小时 ``` require __DIR__ . '/vendor/autoload.php'; use Carbon\Carbon; $now = Carbon::now(); echo $now->year . "\n"; echo $now->month . "\n"; echo $now->day . "\n"; echo $now->hour . "\n"; echo $now->second . "\n"; echo $now->dayOfWeek . "\n"; echo $now->dayOfYear . "\n"; echo $now->weekOfMonth . "\n"; echo $now->daysInMonth . "\n"; ``` ### 流式 API ``` require __DIR__ . './../vendor/autoload.php'; use Carbon\Carbon; $dt = Carbon::create(); $dt->year(2019)->month(5)->day(6)->hour(16)->minute(12)->second(53); echo $dt . "\n"; // 2019-05-06 16:12:53 $dt2 = Carbon::create(); $dt2->setDate(2019, 5, 6)->setTime(16, 12, 53); echo $dt2 . "\n"; // 2019-05-06 16:12:53 $dt3 = Carbon::create(); $dt3->setDate(2019, 5, 6)->setTime(16, 12, 53); echo $dt3 . "\n"; // 2019-05-06 16:12:53 $dt3 = Carbon::Now(); $dt3->setTime(0, 0,0); echo $dt3 . "\n"; // 2020-08-31 00:00:00 ``` ## 秒,时,天,月,年,世纪的开始于结束 ``` require __DIR__ . './../vendor/autoload.php'; use Carbon\Carbon; $dt = Carbon::now(); echo "\n月开始结束\n"; echo $dt->copy()->startOfMonth() . "\n"; echo $dt->copy()->endOfMonth() . "\n"; echo "\n年开始结束\n"; echo $dt->copy()->startOfYear() . "\n"; echo $dt->copy()->endOfYear() . "\n"; echo "\n天开始结束\n"; echo $dt->copy()->startOfDay() . "\n"; // 2020-08-31 00:00:00 echo $dt->copy()->endOfDay() . "\n"; // 2020-08-31 23:59:59 echo "\n小时开始结束\n"; echo $dt->copy()->startOfHour() . "\n"; // 2020-08-31 15:00:00 echo $dt->copy()->endOfHour() . "\n"; // 2020-08-31 15:59:59 ``` ### 加减秒,分,时,天,月,年的时间 ``` require __DIR__.'./../vendor/autoload.php'; use Carbon\Carbon; $dt = Carbon::now(); echo $dt."\n"; // 2020-08-31 15:31:04 echo $dt->copy()->add(1)."\n"; // 2020-08-31 15:31:04 echo $dt->copy()->addDay()."\n"; // 2020-09-01 15:31:04 echo $dt->copy()->addMinutes(10)."\n"; // 2020-09-01 15:31:04 echo $dt->copy()->subDays(1)."\n"; // 2020-08-30 15:31:04 ```