php datetime 对象,PHP DateTime 对象和 Date 函数的 Demo
DateTime對象
//設置時間時區
date_default_timezone_set("PRC");
$dateFormat = "Y-m-d";
$dateTimeFormat = "Y-m-d H:i:s";
//獲取當前時間
$date = new DateTime();
echo $date->format($dateTimeFormat) . "\n";
//時間2015-01-01加上7年5月4天4小時3分鐘2秒
$date = new DateTime("2015-01-01");
$addDate = new DateInterval("P7Y5M4DT4H3M2S");
$date->add($addDate);
echo $date->format($dateTimeFormat) . "\n";
//時間2015-05-29加上1年2月3天
$date = new DateTime("2015");
$date->add(new DateInterval("P1Y2M3D"));
echo $date->format($dateFormat) . "\n";
//當前時間加上3小時2分鐘1秒
$date = new DateTime();
$date->add(new DateInterval("PT3H2M1S"));
echo $date->format($dateTimeFormat) . "\n";
$date = DateTime::createFromFormat($dateFormat, "2009-02-15");
echo $date->format($dateTimeFormat) . "\n";
$date = new DateTime();
$date->setDate(2222, 12, 22);
echo $date->format($dateFormat) . "\n";
$date = new DateTime();
$date->setTime(14, 55);
echo $date->format($dateTimeFormat) . "\n";
$date = new DateTime();
$date->setTimestamp(1171502725);
echo $date->format($dateTimeFormat) . "\n";
//時間的比較
$Today = new DateTime();
$Tomorrow = new DateTime();
$Tomorrow->add(new DateInterval("P1D"));
$diff = $Tomorrow->diff($Today);
echo "Difference: " . $diff->format("%m month, %d days (total: %a days)") . "\n";
if ($Today < $Tomorrow) {
echo "Today is before Tomorrow!\n";
}
//獲取時間戳以及輸出格式化的時間戳
$date = new DateTime();
echo $date->getTimestamp() . "\n";
echo $date->format($dateTimeFormat) . "\n";
date 函數
//默認時區
date_default_timezone_set("PRC");
echo "今天:" . date("Y-m-d", time()) . "
";
echo "今天:" . date("Y-m-d", strtotime("18 june 2008")) . "
";
echo "昨天:" . date("Y-m-d", strtotime("-1 day")) . "
";
echo "明天:" . date("Y-m-d", strtotime("+1 day")) . "
";
echo "一周后:" . date("Y-m-d", strtotime("+1 week")) . "
";
echo "一周零兩天四小時兩秒后:" . date("Y-m-d G:H:s", strtotime("+1 week 2 days 4 hours 2 seconds")) . "
";
echo "下個星期四:" . date("Y-m-d", strtotime("next Thursday")) . "
";
echo "上個周一:" . date("Y-m-d", strtotime("last Monday")) . "
";
echo "一個月前:" . date("Y-m-d", strtotime("last month")) . "
";
echo "一個月后:" . date("Y-m-d", strtotime("+1 month")) . "
";
echo "十年后:" . date("Y-m-d", strtotime("+10 year")) . "
";
總結
以上是生活随笔為你收集整理的php datetime 对象,PHP DateTime 对象和 Date 函数的 Demo的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何设置管理员密码(如何设置管理员密码为
- 下一篇: 360安卓开心消消乐下载电脑版下载电脑版