DateTime::__construct
(PHP 5 >= 5.2.0, PHP 7)
DateTime :: __ construct - date_create - 返回新的DateTime对象
描述
面向对象的风格
public DateTime::__construct ([ string $time
= "now" [, DateTimeZone $timezone
= NULL
]] )
程序风格
DateTime date_create ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
返回新的DateTime对象。
参数
time
日期/时间字符串。有效格式在日期和时间格式中进行说明。
在此处输入“now”以获取使用$timezone
参数时的当前时间。
timezone
表示时区的DateTimeZone对象$time
。
如果$timezone
省略,则将使用当前时区。
注意:
$timezone
当$time
参数是UNIX时间戳(例如@ 946684800)或指定时区(例如2010-01-28T15:00:00 + 02:00)时,参数和当前时区将被忽略。
返回值
返回一个新的DateTime实例。程序风格FALSE
在失败时返回。
错误/异常
发生错误时发出异常。
更新日志
版 | 描述 |
---|---|
5.3.0 | 如果时间包含无效的日期/时间格式,则现在抛出异常。以前发生了一个错误。 |
7.1 | 从现在起微秒充满实际价值。不与'00000'。 |
例子
示例 #1 DateTime::__construct() example
面向对象的风格
<?php
try?{
????$date?=?new?DateTime('2000-01-01');
}?catch?(Exception?$e)?{
????echo?$e->getMessage();
????exit(1);
}
echo?$date->format('Y-m-d');
?>
程序风格
<?php
$date?=?date_create('2000-01-01');
if?(!$date)?{
????$e?=?date_get_last_errors();
????foreach?($e['errors']?as?$error)?{
????????echo?"$error\n";
????}
????exit(1);
}
echo?date_format($date,?'Y-m-d');
?>
上面的例子会输出:
2000-01-01
示例 #2 Intricacies of DateTime::__construct()
<?php
//?Specified?date/time?in?your?computer's?time?zone.
$date?=?new?DateTime('2000-01-01');
echo?$date->format('Y-m-d?H:i:sP')?.?"\n";
//?Specified?date/time?in?the?specified?time?zone.
$date?=?new?DateTime('2000-01-01',?new?DateTimeZone('Pacific/Nauru'));
echo?$date->format('Y-m-d?H:i:sP')?.?"\n";
//?Current?date/time?in?your?computer's?time?zone.
$date?=?new?DateTime();
echo?$date->format('Y-m-d?H:i:sP')?.?"\n";
//?Current?date/time?in?the?specified?time?zone.
$date?=?new?DateTime(null,?new?DateTimeZone('Pacific/Nauru'));
echo?$date->format('Y-m-d?H:i:sP')?.?"\n";
//?Using?a?UNIX?timestamp.??Notice?the?result?is?in?the?UTC?time?zone.
$date?=?new?DateTime('@946684800');
echo?$date->format('Y-m-d?H:i:sP')?.?"\n";
//?Non-existent?values?roll?over.
$date?=?new?DateTime('2000-02-30');
echo?$date->format('Y-m-d?H:i:sP')?.?"\n";
?>
上面的例子会输出类似于:
2000-01-01 00:00:00-05:00
2000-01-01 00:00:00+12:00
2010-04-24 10:24:16-04:00
2010-04-25 02:24:16+12:00
2000-01-01 00:00:00+00:00
2000-03-01 00:00:00-05:00
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com