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】忘れてしまう日付の比較関連【個人メモ】

Last updated at Posted at 2017-10-05

はじめに

これは個人的なメモです。
毎回調べながら書いているのでいっそのこと・・・調べていることを書いておこうという話。
日付の比較には個人的にDateTimeクラスを使用している。

DateTime とは?

DateTime クラス 
(PHP 5 >= 5.2.0, PHP 7)
日付と時刻をあらわします。

PHP DateTime

文字列の時でも大丈夫か?

大丈夫!

$sample = array(
        'date_sample1'  => '20170101',
        'date_sample2'  => '20180101'
    );
    

$date_1 = new Datetime($sample['date_sample1']);
$date_2 = new Datetime($sample['date_sample2']);
print_r($date_1);
print_r($date_2);

以下は結果

DateTime Object
(
    [date] => 2017-01-01 00:00:00.000000
    [timezone_type] => 3
    [timezone] => UTC
)
DateTime Object
(
    [date] => 2018-01-01 00:00:00.000000
    [timezone_type] => 3
    [timezone] => UTC
)

比較は関数使え

// 比較
$diff = $date_1->diff($date_2);
print_r($diff);

結果

DateInterval Object
(
    [y] => 1
    [m] => 0
    [d] => 0
    [h] => 0
    [i] => 0
    [s] => 0
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 0
    [days] => 365
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)

diff で比較した際、差分の日付の取得の仕方

$diff = $date_1->diff($date_2)->format('%R%a');

%R%a を使用すると、正負の値が取得できる。

$diff = intval($date_1->diff($date_s)->format('%R%a'));

で取得する際に、intval でint型にすればなおさら取得しやすい!

比較はIF文でも可能

// if 文での比較
if($date_1 > $date_2) {
    print('date_1の方が大きい');
}
else {
    print('date_2の方が大きい');
}

結果

date_2の方が大きい
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?