Carbonで今日の日付/現在時刻を表示

### 今日の日付のみを日本語で表示

use Carbon\Carbon;
setlocale(LC_ALL, 'ja_JP.UTF-8');
$this->date = Carbon::today()->formatLocalized("%Y年%m月%d日(%a)");

### 今日の日時を日本語で表示

$this->date = Carbon::now()->formatLocalized("%Y年%m月%d日(%a) %H時%M分");

日付の場合は、::today()ではなく、::now()に変更する。today()だと、日付までのunix timeしか持たないので、H時M分は00時00分になる。
こんな凡ミスに気づか付きに悶絶してしまいました。

Vue.jsでCarbonの代わりにmoment.jsを使用する

### view

<template v-for="m in messages>
  // 省略
  <span>@{{ m.created_at |  moment  }}</span>
  // 省略
</template>

### script
– Vueのmethods内でmoment()を呼び出し、filtersでformatを指定する

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js" type="text/javascript"></script>
<script>
new Vue({
  el: '#app',
  filters: {
   moment: function (date) {
   return moment(date).format('MM/DD HH:mm');
   }
  },
  data: {
  // 省略
  },
   methods: {
   // 省略
   moment: function () {
    return moment();
   }
   },
   mounted(){
   // 省略
   }
});
</script>

momentはvueの中で指定しないとうまく動かない。
make:resourceでサーバ側でcarbonで整形することも考えたが、コントローラの処理が複雑な為、クライアント側でフォーマット化する。

Carbonを使ってみよう

require "vendor/autoload.php";

use Carbon\Carbon;

$dt = new Carbon();
echo $dt . "<br>";

$dt = Carbon::now();
echo $dt . "<br>";

$dt = new Carbon("2019-05-09");
echo $dt . "<br>";

$dt = Carbon::today();
echo $dt . "<br>";

$dt = Carbon::tomorrow();
echo $dt . "<br>";

$dt = Carbon::yesterday();
echo $dt . "<br>";

$dt = Carbon::parse("2019-05-07 10:30:30");
echo $dt . "<br>";

2019-05-07 20:54:17
2019-05-07 20:54:17
2019-05-09 00:00:00
2019-05-07 00:00:00
2019-05-08 00:00:00
2019-05-06 00:00:00
2019-05-07 10:30:30

なるほどー、確かに使いやすいかもね~

Carbon and php

Carbon is a package that extends PHP’s DataTime class, making it possible to manipulate dates and times more intuitively and more simply.

なるほど、道理でLaravelに使われている訳だ。

composerを入れます。

[vagrant@localhost test]$ curl -sS https://getcomposer.org/installer | php
All settings correct for using Composer
Downloading...

Composer (version 1.8.5) successfully installed to: /home/vagrant/local/app/test/composer.phar
Use it: php composer.phar

続いて、carbonを入れます。
[vagrant@localhost test]$ php composer.phar require nesbot/carbon
No composer.json in current directory, do you want to use the one at /home/vagrant/local/app? [Y,n]? y
Using version ^2.17 for nesbot/carbon
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 4 installs, 0 updates, 0 removals
– Installing symfony/polyfill-mbstring (v1.11.0): Loading from cache
– Installing symfony/contracts (v1.0.2): Loading from cache
– Installing symfony/translation (v4.2.8): Downloading (100%)
– Installing nesbot/carbon (2.17.1): Downloading (100%)
symfony/contracts suggests installing psr/cache (When using the Cache contracts)
symfony/contracts suggests installing psr/container (When using the Service contracts)
symfony/contracts suggests installing symfony/cache-contracts-implementation
symfony/contracts suggests installing symfony/service-contracts-implementation
symfony/translation suggests installing symfony/config
symfony/translation suggests installing symfony/yaml
symfony/translation suggests installing psr/log-implementation (To use logging capability in translator)
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Writing lock file
Generating autoload files


Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.

ん、間違えたか。jsonの使うところが違うな。

やり直します。
[vagrant@localhost test]$ php composer.phar require nesbot/carbon
No composer.json in current directory, do you want to use the one at /home/vagrant/local/app? [Y,n]? n
Using version ^2.17 for nesbot/carbon
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 4 installs, 0 updates, 0 removals
– Installing symfony/polyfill-mbstring (v1.11.0): Loading from cache
– Installing symfony/contracts (v1.0.2): Loading from cache
– Installing symfony/translation (v4.2.8): Loading from cache
– Installing nesbot/carbon (2.17.1): Loading from cache
symfony/contracts suggests installing psr/cache (When using the Cache contracts)
symfony/contracts suggests installing psr/container (When using the Service contracts)
symfony/contracts suggests installing symfony/cache-contracts-implementation
symfony/contracts suggests installing symfony/service-contracts-implementation
symfony/translation suggests installing symfony/config
symfony/translation suggests installing symfony/yaml
symfony/translation suggests installing psr/log-implementation (To use logging capability in translator)
Writing lock file
Generating autoload files

OK、上手くいきましたね^^
では早速使っていきましょう~

Carbon インスタンス

// $dt = new Carbon();
// $dt = Carbon::now();
// $dt = new Carbon('2016-12-20 11:32:23');
//$dt = new Carbon('tomorrow');
//$dt = Carbon::today();
//$dt = Carbon::tommorow();
// $dt = Carbon::yesterday();
// $dt = Carbon::parse('2016-12-12 11:32:32');
// $dt = Carbon::create(2020,12, 12, 11, 32, 32);
$dt = Carbon::createFromFormat('Y/m/d H', '2016/12/20 20');

日時情報の取得

$dt = Carbon::now();
//echo $dt->year . PHP_EOL;
//echo $dt->month . PHP_EOL;
//echo $dt->day . PHP_EOL;
//echo $dt->hour . PHP_EOL;
//echo $dt->minute . PHP_EOL;
//echo $dt->second . PHP_EOL;
//echo $dt->dayOfWeek . PHP_EOL;
//echo $dt->dayOfYear . PHP_EOL;
//echo $dt->weekOfMonth . PHP_EOL;
//echo $dt->weekOfYear . PHP_EOL;
// echo $dt->timestamp . PHP_EOL;
// echo $dt->tzName . PHP_EOL;
echo $dt->format('Y年m月d日') . PHP_EOL;

日付判定

//var_dump($dt->isToday()) . PHP_EOL;
//var_dump($dt->isTommorow()) . PHP_EOL;
//var_dump($dt->isYesterday()) . PHP_EOL;
//var_dump($dt->isFuture()) . PHP_EOL;
//var_dump($dt->isPast()) . PHP_EOL;
//var_dump($dt->isLeapYear()) . PHP_EOL;
//var_dump($dt->isWeekday()) . PHP_EOL;
//var_dump($dt->isWeekend()) . PHP_EOL;
//var_dump($dt->isSameDay(Carbon::now())) . PHP_EOL;

変数をとって、日時を比較

$dt1 = Carbon::create(2020, 10, 1);
$dt2 = Carbon::create(2020, 11, 1);

// var_dump($dt1->eq($dt2)) . PHP_EOL;
//var_dump($dt1->gt($dt2)) . PHP_EOL;
//var_dump($dt1->lt($dt2)) . PHP_EOL;
//var_dump(Carbon::create(2010, 10, 10)->between($dt1, $dt2)) . PHP_EOL;
//echo $dt1->max($dt2) . PHP_EOL;
//echo $dt1->min($dt2) . PHP_EOL;

日付計算

// echo $dt->addYear(). PHP_EOL;
//echo $dt->addYears(3). PHP_EOL;
//echo $dt->subYears(3). PHP_EOL;
//echo $dt->addWeekdays(3). PHP_EOL;
//echo $dt->addWeekdays(3)->addWeekHours(3)->addWeekMinutes(3). PHP_EOL;

コピーメソッド

$dt = Carbon::now();
echo $dt->copy()->addYear() . PHP_EOL;
echo $dt . PHP_EOL;

日時指定

//echo $dt->startOfDay() . PHP_EOL;
//echo $dt->endOfDay() . PHP_EOL;
//echo $dt->startOfMonth() . PHP_EOL;
//echo $dt->endOfMonth() . PHP_EOL;
//echo $dt->startOfWeek() . PHP_EOL;
//echo $dt->endOfWeek() . PHP_EOL;
//echo $dt->next(Carbon::MONDAY) . PHP_EOL;
//echo $dt->previous(Carbon::MONDAY) . PHP_EOL;
//echo $dt->firstOfMonth(Carbon::MONDAY) . PHP_EOL;
//echo $dt->lastOfMonth(Carbon::MONDAY) . PHP_EOL;
//echo $dt->nthOfMonth(3, Carbon::MONDAY) . PHP_EOL;

日時の差

$dt1 = Carbon::create(2020, 10, 1);
$dt2 = Carbon::create(2020, 11, 1);

//echo $dt1->diffInDays($dt2) . PHP_EOL;
//echo $dt1->diffInHours($dt2) . PHP_EOL;
//echo $dt1->diffInMinutes($dt2) . PHP_EOL;
//echo $dt1->diffForHumans($dt2) . PHP_EOL;

setTestNow()を使った判定

$dt = Carbon::now();
$birthday = Carbon::create(1990, 10, 1);
Carbon::setTestNow(Carbon::create(2020, 10, 1));
echo Carbon::now() . PHP_EOL;
if($birthday->isBirthday(Carbon::now())){
  echo ':)' . PHP_EOL;
} else {
  echo ':<' . PHP_EOL;

Composerとcarbon

composer
Composerをインストールします。

curl -sS https://getcomposer.org/installer | php

続いてcarbonをインストール

[vagrant@localhost php]$ php composer.phar require nesbot/carbon

carbon.php

require 'vendor/autoload.php';

use Carbon\Carbon;

$dt = new Carbon();
echo $dt . PHP_EOL;
[vagrant@localhost php]$ php carbon.php
2016-11-14 11:24:43
[vagrant@localhost php]$ date
2016年 11月 14日 月曜日 11:24:53 JST