LoginSignup
48
44

More than 3 years have passed since last update.

php Carbonと標準関数の対応表

Last updated at Posted at 2015-07-15

Carbonとは?

http://carbon.nesbot.com/
phpの日付操作を感覚的に行えるライブラリです。
特に良い点としては、直感的に記述できることと、

現在の関わる処理をテストしやすくすることです。

例えば、現在時刻を返す場合は

//std
time()
//carbon
Carbon::now()->timestamp

となります。
標準関数を利用している場合は、現在時刻はサーバーに依存してしまいますが、
Carbonを利用すれば、

$now = '2015-07-07';
Carbon::setTestNow(Carbon::parse($now));

とするだけで、現在時刻が指定された時刻になります。

比較

では実際に比較していきます。

CarbonはCarbonインスタンス、標準関数はタイムスタンプを返します。

Carbonを特定の形式に変換するには下記の方法などがあります。

$carbon = Carbon::parse('2015-07-07')

$carbon->timestamp; //タイムスタンプ
$carbon->format('Y年m月d日'); //date()と同じ

また、strtotime関数の挙動が心配な場合はDatetimeオブジェクトを利用しましょう。

$dt = new Datetime('2015-07-07');
$dt->format('Y年m月d日');

現在

//Carbon
Carbon::now();

//std
time();

今日

//Carbon
Carbon::today();

//std
strtotime('today');

今週月曜日(月曜日始まり)

//Carbon
Carbon::now()->startOfweek();

//std
strtotime('last monday', strtotime('tomorrow'));

今週月曜日(日曜始まり)

//Carbon
Carbon::parse('Monday this week');

//std
strtotime('Monday this week');

今月末

 //Carbon
 Carbon::now()->endOfMonth()

 //std
 strtotime(date('Y-m-t'));
 strtotime('last day of this month');

先月末

//Carbon
Carbon::parse('- 1 month')->endOfMonth()

//std
strtotime('last day of previous month');

その他、日付を加減算したり、異なるタイムゾーンでの比較もできちゃいます!

48
44
4

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
48
44