PHPで日付・時刻を取得したり設定したりする方法
PHPで日付・時刻を扱うオブジェクトについて。
DateTime
文字列や整数からDateTimeクラスを作成する方法です。DateTimeクラスから日付文字列の取得はDateTime->format()を使用します。
文字列から DateTime クラスを生成する
DateTimeクラス生成時に日付・時刻の文字列をパラメータで設定します。
$firstDate = new DateTime('2019-06-30 23:59:59');
echo $firstDate->format('Y/m/d H:i:s'); // 2019/06/30 23:59:59
整数を使って DateTime クラスに設定する
DateTimeクラス生成後にsetDate()やsetTime()で日付・時刻を設定します。
$year = 2019;
$month = 7;
$day = 1;
$firstDate = new DateTime();
$firstDate->setDate($year, $month, $day);
$firstDate->setTime(0, 0, 0);
echo $firstDate->format('Y/m/d H:i:s'); // 2019/07/01 00:00:00
現在時刻の取得
パラメータなしでDateTimeクラスを生成すると現在時刻を取得できます。
$now = new DateTime();
タイムスタンプ
time()を使うと、現在のタイムスタンプが取得できます。タイムスタンプはUnixエポック(1970年1月1日 00:00:00 GMT)からの通算秒(整数値)です。
$timestamp = time();
idate('書式', タイムスタンプ)で日付・時刻を整数で取得できます。
| 書式文字列 | 取得する値 |
|---|---|
| Y | 年(4桁) |
| y | 年(下2桁または1桁) |
| m | 月 |
| d | 月の日 |
| H | 時(24時間単位) |
| h | 時(12時間単位) |
| i | 分 |
| s | 秒 |
