1
3

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 3 years have passed since last update.

【PHP】日付の簡単な比較

Last updated at Posted at 2020-10-18

PHPer の皆さん、日付の比較どうしてますか〜?

おそらく

・strtotime関数
・DateTimeクラス
・Carbonライブラリ

などを使用されてるかと思います。

しかし、簡単な比較であれば、
文字列のまま比較演算子を使用できるのをご存知でしょうか。

自分もたまたまできることに気づいたので、
どの形式まで日付を比較できるのかを試してみたので、ご紹介します。

まずは YYYY-mm-dd 形式の比較です。

'2020-09-09' > '2020-09-08', //true
'2020-09-09' >= '2020-09-08', //true
'2020-09-09' > '2020-09-09', // false
'2020-09-09' >= '2020-09-09', //true

期待通り、比較結果がえられました。

続いて上記から 0 を省いてみます。

'2020-9-9' > '2020-9-8', //true
'2020-9-9' >= '2020-9-8', //true
'2020-9-9' > '2020-9-9', // false
'2020-9-9' >= '2020-9-9', //true

大丈夫そうです。

続いて YYYY/mm/dd 形式で比較してみましょう。(0 を省くのも一緒にやっちゃいます)

'2020/09/09' > '2020/09/08', //true
'2020/09/09' >= '2020/09/08', //true
'2020/09/09' > '2020/09/09', // false
'2020/09/09' >= '2020/09/09', //true
'2020/9/9' > '2020/9/8', //true
'2020/9/9' >= '2020/9/8', //true
'2020/9/9' > '2020/9/9', // false
'2020/9/9' >= '2020/9/9', //true

問題ないですね。

さらに日時で比較してみましょう。

'2020-09-09 09:09:09' > '2020-09-09 09:09:08', //true
'2020-09-09 09:09:09' >= '2020-09-09 09:09:08', //true
'2020-09-09 09:09:09' > '2020-09-09 09:09:09', // false
'2020-09-09 09:09:09' >= '2020-09-09 09:09:09', //true

'2020-9-9 9:9:9' > '2020-9-9 9:9:8', //true
'2020-9-9 9:9:9' >= '2020-9-9 9:9:8', //true
'2020-9-9 9:9:9' > '2020-9-9 9:9:9', // false
'2020-9-9 9:9:9' >= '2020-9-9 9:9:9', //true

'2020/09/09 09:09:09' > '2020/09/09 09:09:08', //true
'2020/09/09 09:09:09' >= '2020/09/09 09:09:08', //true
'2020/09/09 09:09:09' > '2020/09/09 09:09:09', // false
'2020/09/09 09:09:09' >= '2020/09/09 09:09:09', //true

'2020/9/9 9:9:9' > '2020/9/9 9:9:8', //true
'2020/9/9 9:9:9' >= '2020/9/9 9:9:8', //true
'2020/9/9 9:9:9' > '2020/9/9 9:9:9', // false
'2020/9/9 9:9:9' >= '2020/9/9 9:9:9' //true

すべて問題ありませんね!

まとめ

・簡単な比較であれば日付を文字列のまま比較できる
・形式は「Y-m-d」「Y/m/d」どちらも OK
・時間が含まれていても OK
・0 が省かれていても OK

1
3
1

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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?