LoginSignup
1
2

More than 3 years have passed since last update.

【Laravel】Carbon まとめ

Posted at

laravelでサービスを作る上で日時操作をする機会が多かったので、よく使っているメソッドなどをまとめました。

Carbonクラス

CarbonクラスはDateTimeクラスから継承された日付操作ライブラリ。
Laravelには標準搭載されている

使用方法

use Carbon\Carbon;の宣言をすることで簡単に使用できる。

取得方法

$date = new Carbon();//インスタンス作成

使用用途によって文字列を入れてインスタンス化可能

//ex)now:2020-01-01 12:23:34:121212

new Carbon('now'); //2020-01-01 12:23:34:121212
new Carbon('today'); //2020-01-01 00:00:00:000000
new Carbon('tomorrow'); //2020-01-02 00:00:00:000000
new Carbon('yesterday'); //2019-12-31 00:00:00:000000

//時を進めることも可能
new Carbon('+10 minutes'); //2020-01-11 12:33:34:121212
new Carbon('+10 day'); //2020-01-11 12:23:34:121212

//スタティック
$date = Carbon::now(); /2020-01-01 12:23:34:121212

インスタンスより欲しい日時を取得

$date = Carbon::now();

$date->year; // 2020
$date->month; // 1
$date->day; // 1
$date->hour; // 12
$date->minute; // 23
$date->second; //34

出力フォーマット変更

$date->format('Y年m月d日h時i分s秒')//2020年1月1日12時23分34秒
//時間はhで12時間表示、Hで24時間表示

差分を計算

$date1 = new Carbon('2020-01-01');
$date2 = new Carbon('2020-12-25');

// 分
$dt1->diffInMinutes($dt2); // 516960分

// 時間
$dt1->diffInHours($dt2); // 8616時間

// 日
$dt1->diffInDays($dt2); // 359日

// 週
$dt1->diffInWeeks($dt2); // 51週

// 年
$dt1->diffInYears($dt2); // 0年

参考文献

公式サイト https://carbon.nesbot.com/

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2