LoginSignup
279
284

More than 1 year has passed since last update.

PHPで日付関数を使いこなす(date, strtotime)

Last updated at Posted at 2015-03-09

1. date関数

date(フォーマット)
date(フォーマット, タイムスタンプ)
  • date関数は引数を1つ(or2つ)持てる
    • 第1引数:フォーマット(string)
    • 第2引数:タイムスタンプ(int)
  • 引数1つの時:「現在の時刻」を「指定したフォーマット」で出力
  • 引数2つの時:「第2引数のタイムスタンプ」を「指定したフォーマット」で出力
  • 戻り値はstring

使用例

下記、2015年3月10日(火)朝6時に叩いたコマンドである。

<?php

date_default_timezone_set('Asia/Tokyo');

echo date("Y/m/d H:i:s") . "\n"; //「2015/03/10 06:00:00」
echo date("Y/m/01") . "\n"; //「2015/03/01」
echo date("Y/m/t") . "\n"; //「2015/03/31」

$w = date("w");
$week_name = array("日", "月", "火", "水", "木", "金", "土");

echo date("Y/m/d") . "($week_name[$w])\n"; //「2015/03/10(火)」
  • date_default_timezone_set('Asia/Tokyo');:まずタイムゾーンの設定をすること。
  • Y:年(4桁表記)
    • y:年(2桁表記)
  • m:月(2桁表記)
    • n:月(先頭にゼロつけない)
  • d:日(2桁表記)
    • j:日(先頭にゼロつけない)
  • H:時間(24時間単位)
    • h:時間(12時間単位)
  • i:分
  • s:秒
  • t:指定した月の日数
  • w:曜日番号(0[日曜]から6[土曜]の値)
  • .:文字列連結
  • \n:改行

2. strtotime関数

strtotime(日時)
strtotime(日時, タイムスタンプ)
  • strtotime関数は引数を1つ(or2つ)持てる
    • 第1引数:日時(string)。相対日時や絶対日時を指定可能。
    • 第2引数:タイムスタンプ(int)
  • 引数1つの時:「現在」を基準とした、「第1引数の日時」のタイムスタンプを出力
  • 引数2つの時:「第2引数のタイムスタンプ」を基準とした、「第1引数の日時」のタイムスタンプを出力
  • 戻り値はint

使用例

下記、2015年3月10日(火)朝6時に叩いたコマンドである。

<?php

date_default_timezone_set('Asia/Tokyo');

echo date("Y/m/d H:i:s", strtotime('-1 day')) . "\n"; //「2015/03/09 06:00:00」
echo date("Y/m/d", strtotime('last Saturday')) . "\n"; //「2015/03/07」
echo date("Y/m/d 10:00:00", strtotime('last Saturday', strtotime('2015-03-07'))); //「2015/02/28 10:00:00」
echo date("Y/m/d 10:00:00", strtotime('last Saturday', strtotime('2015-03-03') + 7 * 24 * 60 * 60)); //「2015/03/07 10:00:00」
  • strtotimeの第1引数にはlast Saturday'2015-03-07'などが使える。
    • last Saturdayのような相対日時を使う場合、第2引数なしなら「現在から見たlast Saturday」、第2引数ありなら「タイムスタンプの日付から見たlast Saturday」
  • タイムスタンプに7 * 24 * 60 * 60を足したら7日後を表す。

※参考URL
▼[PHP]date
http://php.net/manual/ja/function.date.php
▼[PHP]strtotime
http://php.net/manual/ja/function.strtotime.php
▼strtotimeの引数に有効な書式
http://php.net/manual/ja/datetime.formats.php

279
284
2

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
279
284