LoginSignup
1
0

More than 5 years have passed since last update.

CakePHP3でSELECTするときに日付をフォーマットして出力する方法

Posted at

やりたいこと

DBから日付のデータをフォーマットを指定して出力する

方法

0.データの準備

#テーブルの作成
create table samples (
id int,
username varchar(255),
created date
);

#データの挿入
inser into samples (id, username, created) 
values(1, user1, 2018-05-04);

1.日付のフォーマットを定義する

$newFormat = $this->Samples->find()
                  ->func()
                  ->date_format([
                    'created' => 'literal' //フォーマットするカラムの指定
                    "'%Y/%m'" => 'literal' //フォーマットを指定
                  ]);

まず指定したいフォーマットを格納する変数を用意します。
フォーマットの年月日部分は%Yのように%○で1セットです。
今回の例だと2018/5のような形で出力されます。

"と'の使用を間違えないようにしてください。
'literal'部分はどういう働きをしているのかよくわかりませんでしたが、必ず指定しなくてはいけないみたいです。

2.新しいフォーマットをselect中で指定して出力する


$newFormat_dates = $this->Samples->find()
                  ->select(['newformat_created' => $newFormat])//任意のキーを設定(この例ではnewformat_createdとしています)し、$newFormatを指定します。
                  ->all();

あとは先程作成した$newFormatを使用してSELECTしてあげると指定したフォーマットでデータを抽出できます。

ポイントは'newformat_created' => $newFormatの部分で、必ず新しくキーを設定してあげなければなりません。指定しないとエラーになります。
新しいキーは任意の名前で大丈夫です。


$foreach($newFormat_dates as $newFormat_date){
     echo $newFormat_date->newformat_created;//新しいフォーマットで日付を出力
}

これで指定したフォーマットで年月日を出力できます。

1
0
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
0