LoginSignup
0
0

More than 3 years have passed since last update.

[PHP]一番早い日時, 一番遅い日時を返すには?

Posted at

結論

min(), max()を使えば良いです。

コード

sample.php
<?php

$oldest_datetime = new DateTimeImmutable('2020-08-15 09:00:00');
$datetime        = new DateTimeImmutable('2020-08-15 10:00:00');
$latest_datetime = new DateTimeImmutable('2040-08-15 11:00:00');

var_dump(min($oldest_datetime, $datetime, $latest_datetime));
var_dump(max($oldest_datetime, $datetime, $latest_datetime));

// 配列で渡してもOK
$datetimes = [ $oldest_datetime, $datetime, $latest_datetime ];

var_dump(min($datetimes));
var_dump(max($datetimes));
$ php sample.php
object(DateTimeImmutable)#1 (3) {
  ["date"]=>
  string(26) "2020-08-15 09:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}
object(DateTimeImmutable)#3 (3) {
  ["date"]=>
  string(26) "2040-08-15 11:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}
object(DateTimeImmutable)#1 (3) {
  ["date"]=>
  string(26) "2020-08-15 09:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}
object(DateTimeImmutable)#3 (3) {
  ["date"]=>
  string(26) "2040-08-15 11:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}

ポイント

  • min(), max()なら誰でもある程度は挙動を知ってます。オレオレ関数をわざわざ作る必要はありません。
  • DateTimeImmutable, Datetimeクラスは比較演算子が使えます。なのでmin(), max()による早い/遅いの比較が可能です。エポック秒などの数字に変換させる必要はありません。

min - PHP

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