LoginSignup
0
2

More than 5 years have passed since last update.

PHP time

Last updated at Posted at 2017-04-10

UNIX TIMESTAMP

協定世界時(UTC)を基準にした1970年1月1日の0時0分0秒からの経過秒数

strtotime()

英文形式の日付を Unix タイムスタンプに変換する。

$a2 =strtotime("+1 week");
echo date("y/m/d", $a2); // 17/04/17
echo strtotime("4 months ago"); // 1481358756

UNIX TIMESTAMPを年月日に変換

$a = time(); // 1491798124
echo date("y/m/d", $a); // 17/04/10

strtotimeを年月日に変換

strtotime()で取得されたタイムスタンプを年月日に変換

$a1 = strtotime("yesterday");
echo date("y/m/d", $a1); // 17/04/09

strtotime('Monday',time());

date()

現在時刻をフォーマット文字列に沿って作成し、日付文字列を返す関数

フォーマットで使える文字列
Y 4桁の年 date('Y'); // 2017
y 2桁の年 date('y'); // 17
m 2桁の月で、先頭に0が付く date('m'); // 04
n 先頭に0の付かない月 date('n'); // 4
d 2桁の日で、先頭に0が付く date('d'); // 20
j 2桁の日で、先頭に0が付かない date('j'); // 20
H又はh 2桁の時(24時間単位 date('H'); // 08
i 2桁の分で、先頭に0が付く date('i'); // 32
s 2桁の秒で、先頭に0が付く date('s'); // 59
echo date('y/m/d'); // 17/04/10
date_default_timezone_set('Japan');
echo '<p>', date('Y/m/d h:i:s');
echo '<p>', date('Y年m月d日 h時i分s秒'),'</p>';
実行結果
2017/04/27 12:04:37
2017年04月27日 12時04分37秒

date_default_timezone_set()

■何故か[H]の部分、時間が7時間遅れて表示されてしまう

echo date('Y/m/d/H/i'); // 2017/04/20/08/45
date_default_timezone_set('Asia/Tokyo');
echo date('Y/m/d/H/i'); // 2017/04/20/15/45
タイムゾーンを日本に指定
date_default_timezone_set('Japan');

mktime()

指定した日時をタイムスタンプ(UNIX TIMESTAMP)という数字で取得することができる

mktime(時,分,秒,月,日,年) 指定した日時のUNIXタイムスタンプを取得する
mktime ( 15, 30, 0, 4, 25, 2017 ); // 1493127000

strftime()

ロケールの設定に基づいてローカルな日付・時間をフォーマットする

フォーマットで使える文字列
%d 日付(2桁で表現) strftime('%d'); //20
%a 曜日(3文字で表現) strftime('%a'); //Thu
%m 月(2桁で表現) strftime('%m'); //04
%b 月(3文字で表現) 月(3文字で表現) //Apr
%y 年(2桁で表現) strftime('%y'); //17
%Y 年(4桁で表現) strftime('%Y'); //2017
%D 月/日/年
%I 2桁で表した12時間制の時間 strftime('%I'); //06
%M 2桁で表した分 strftime('%M'); //09
%H 2 桁であらわした 24 時間制の時間 strftime('%H'); //18

strftime()とdate()を比較

説明  strftime() date()
strftime(%d) date('d') 24
月(2桁) strftime('%m') date('m') 04
月(頭に0を付けない) date('n') 4
月(アルファベット) strftime('%B') date('F') April
strftime('%y') date('y') 17
年(4桁で表現) strftime('%Y') date('Y') 2017
曜日 strftime('%a') date('D') Mon
時(24時間制) strftime('%H') date('H') 11
時(12時間制) strftime('%I') date('h') 11
分(2桁で表現) strftime('%M') date('i') 58
strftime('%S') date('s') 01
複合日付 strftime('%c') 04/24/17 12:15:18
複合日付 date('c') 2017-04-24T12:16:15+09:00
その年の何週目か strftime('%V') date('W') 17
0
2
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
2