---
# System prepended metadata

title: Carbon 常用到的函式

---

# Carbon 常用到的函式

使用Carbon類
```php=
use Carbon\Carbon;
```
laravel 當資料庫為datetime類型時可以直接儲存carbon物件

若要單純顯示字串的話 可以使用toDateTimeString()

範例: 目前時間

```php=
$now = Carbon::now(); //2019-12-11 12:07:59 (object)
$now_string = $now->toDateTimeString(); //2019-12-11 12:07:59 (string)
```
格式化時間至carbon物件
```php=
$carbon =  Carbon::parse('2019-12-11'); //2019-12-11 00:00:00
$carbon =  Carbon::parse('2019-12-11 00:00:00'); //2019-12-11 00:00:00
```
parse無法處理timestamp 必需由另一個函式來處理
```php=
$carbon = Carbon::createFromTimestamp(1575993600); //2019-12-11 00:00:00
```
取得昨天,今天,明天的起始時間
```php=
$yesterday =  Carbon::yesterday();//2019-12-10 00:00:00
$today =  Carbon::today();//2019-12-11 00:00:00
$tomorrow =  Carbon::tomorrow();//2019-12-12 00:00:00
```
```php=
增加1天與減少1天
$tomorrow = $today->addDay();  //2019-12-12 00:00:00
$yesterday = $today->subDay(); 2019-12-11 00:00:00
```
增加與減少複數天
```php=
$someday = $today->addDays(10);  //2019-12-21 00:00:00
$someday = $today->subDay(10); //2019-12-01 00:00:00
```

一些好用的getter
```php=
$year = $now->year; //2019
$month = $now->month; //12
$day = $now->day;//1
$hour = $now->hour;//15  (24小時制)
$minute = $now->minute; //19
$second = $now->second; //40
$timestamp = $now->timestamp //1576049204
$weekOfMonth = $now->weekOfMonth; //2
$daysInMonth = $now->daysInMonth; //31
$englishDayOfWeek = $now->englishDayOfWeek //Wednesday
$englishMonth = $now->englishMonth //December

```
時間比較
```php=
$today = Carbon::today();
$yesterday = Carbon::yesterday();

//大於&大於等於
$today->gt($yesterday); //true
$today->gte($yesterday); //true (包含等於)

//小於&小於等於
$today->lt($yesterday); //false
$today->lte($yesterday); //false (包含等於)
```