Skip to content

Instantly share code, notes, and snippets.

@mia-0032
Created December 23, 2013 14:47
Show Gist options
  • Save mia-0032/8098331 to your computer and use it in GitHub Desktop.
Save mia-0032/8098331 to your computer and use it in GitHub Desktop.
DateTimeクラスを触ってみた
<?php
//現在時刻を取得
$now = new DateTime('now');
//Mysqlのdatetime形式で出力してみたり
echo $now->format('Y-m-d H:i:s');
echo "<hr><br>";
//UNIXタイムでインスタンスを作るときは@をつける
$time = 1356461279;
$time = new DateTime('@' . strval($time));
echo $time->format('c');
echo "<hr><br>";
//比較演算子による比較
$time = time();
$time1 = new DateTime('@' . $time);
$time2 = new DateTime('@' . ($time + 60 * 60));
$time3 = new DateTime(date('Y-m-d H:i:s', $time));
//単なる大小比較はOK
if($time1 < $time2){
echo 'time2のほうが未来';
}
echo "<hr><br>";
//時刻が同じかも==でOK
if($time1 == $time3){
echo 'time1と3は同じ時刻';
}
echo "<hr><br>";
//===で比較すると最初に与えられた引数が違うと一致しないみたい
//これは要注意
if($time1 === $time3){
echo 'time1と3は完全に一致'; //しないよ!
}
echo "<hr><br>";
//型でしばれるよ!!
function printDateTime(DateTime $time){
echo $time->format('r');
echo "<hr><br>";
}
printDateTime($time1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment