---
tags: PHP, Laravel, Backend
---
# Laravel Carbon
## 安裝
`composer require nesbot/carbon`
## 如何使用
可以在`php artisan tinker`裡測試`Carbon\Carbon::now()`
以下是我個人在工作上常使用的範例
```php=
use Carbon\Carbon; // 使用套件
$now = Carbon::now(); // 2021-11-19 14:07:58.592068 Asia/Taipei (+08:00)
$formatedDate = $now->format('Y-m-d H:i:s');
$nowTime = $now->toTimeString(); // 14:15:16
$nowDay = $now->dayOfWeek // 0~6 0 = 星期日
$nowDate = $now->toDateString(); // 2019-12-12
$nowDateTime = $now->toDateTimeString(); // 2019-12-12 14:15:16
$nowTimestamp = $now->timestamp; // 時間戳
```
## 官方範例程式碼
```php=
<?php
use Carbon\Carbon;
printf("Right now is %s", Carbon::now()->toDateTimeString());
printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver')); //implicit __toString()
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();
$nextSummerOlympics = Carbon::createFromDate(2016)->addYears(4);
$officialDate = Carbon::now()->toRfc2822String();
$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;
$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');
$internetWillBlowUpOn = Carbon::create(2038, 01, 19, 3, 14, 7, 'GMT');
// Don't really want this to happen so mock now
Carbon::setTestNow(Carbon::createFromDate(2000, 1, 1));
// comparisons are always done in UTC
if (Carbon::now()->gte($internetWillBlowUpOn)) {
die();
}
// Phew! Return to normal behaviour
Carbon::setTestNow();
if (Carbon::now()->isWeekend()) {
echo 'Party!';
}
// Over 200 languages (and over 500 regional variants) supported:
echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago'
echo Carbon::now()->subMinutes(2)->locale('zh_CN')->diffForHumans(); // '2分钟前'
echo Carbon::parse('2019-07-23 14:51')->isoFormat('LLLL'); // 'Tuesday, July 23, 2019 2:51 PM'
echo Carbon::parse('2019-07-23 14:51')->locale('fr_FR')->isoFormat('LLLL'); // 'mardi 23 juillet 2019 14:51'
// ... but also does 'from now', 'after' and 'before'
// rolling up to seconds, minutes, hours, days, months, years
$daysSinceEpoch = Carbon::createFromTimestamp(0)->diffInDays();
```
## 計算時間差
```php=
Carbon::now()->diffInSeconds ($date, false); // 如果現在時間大於$date,結果會為正負數
Carbon::now()->diffInSeconds ($date, true); // 輸出為絕對值
Carbon::now()->diffInMinutes($date, true) // 現在與$date的分鐘差
Carbon::now()->diffInHours($date, true); // 現在與$date的小時差
Carbon::parse ('2022-01-10')->diffInDays('2021-12-28', false); // -13
Carbon::parse ('2022-01-10')->diffInDays('2021-12-28', true); // 13
```
## 秒數轉時間
```php=
use Carbon\CarbonInterval;
Carbon\CarbonInterval::seconds(10000)->cascade()->forHumans(); // 2小時46分鐘40秒
```
更多用法請見[官方網站](https://carbon.nesbot.com/)
[Github](https://github.com/briannesbitt/carbon)