Created
December 23, 2013 14:47
-
-
Save mia-0032/8098331 to your computer and use it in GitHub Desktop.
DateTimeクラスを触ってみた
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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