0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

php DateTimeを使い1日分と当月分のデータを見る

Last updated at Posted at 2017-06-16

概要

データベースから当日分と当月分のデータを取ってくる処理で
日付で条件絞る時に便利だったDateTimeクラスを実際に実装した流れに乗せて紹介します。
ちなみにデータベースで登録している日付はUNIXTIMEです。

リンク

ソースコード

まずは当日の日付を取得します。

// ソースコード実行時の日付を取得したい場合
$datetime = new DateTime();

// 日付を指定したい場合
$datetime = new DateTime('2017-06-16');

当日分の検索をするためには
一日の__始まりの時__(00:00:00)と__終わりの時間__(23:59:59)を条件に入れないといけないので
そのデータを取得していきます。

// 始まりの時間を取得していきます
$datetime->setTime(00, 00, 00);                // 00:00:00と日付に時間だけをセットする
$startOfDayUnixtime = $datetime->format('U');  // 日付をUNIXTIME形式にして渡す

// 終わりの時間を取得していきます
$datetime->setTime(23, 59, 59);                // 23:59:59と日付に時間だけをセットする
$endOfDayUnixtime = $datetime->format('U');    // 日付をUNIXTIME形式にして渡す

あとはデータベースの検索条件に__始まりの時間__と__終わりの時間__を渡し
その間のデータを取ってきてもらうだけですね!

こんな感じで、当月分のデータも取得します。

// 月の始まりの時間を取得していきます
$datetime->modify('first day of this months');  // 当月の1日を日付をセットする 6月だったら06/01
$datetime->setTime(00, 00, 00);                 // 00:00:00と日付に時間だけをセットする
$startOfMonthUnixtime = $datetime->format('U'); // 日付をUNIXTIME形式にして渡す

// 月の終わりの時間を取得していきます
$datetime->modify('last day of this months');   // 当月の最終日を日付をセットする 6月だったら06/30
$datetime->setTime(23, 59, 59);                 // 23:59:59と日付に時間だけをセットする
$endOfMonthUnixtime = $datetime->format('U');   // 日付をUNIXTIME形式にして渡す

あとはデータベースに条件として時間を渡すだけなので簡単ですね~

おまけ

$datetime->__modify()__がすごく便利で日付計算が簡単に出来ます

$datetime->modify('+1 days');                      // 1日分足す
$datetime->modify('+1 days');                      // 1日分引く
$datetime->modify('+1 weeks');                     // 1週間分足す
$datetime->modify('+1 months + 5 days');            // 1ヶ月と5日分足す
$datetime->modify('first day of this months');     // 当月1日
$datetime->modify('last day of this months');      // 当月末尾
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?