Php 使用设置的时区扩展DateTime对象
我很难用什么样的模式来完成这个任务Php 使用设置的时区扩展DateTime对象,php,design-patterns,datetime,Php,Design Patterns,Datetime,我很难用什么样的模式来完成这个任务 class DateTimeReference { function __construct($time) { $this = new DateTime($time, new DateTimeZone("UTC")); } } $date = new DateTime("now"); // in server time $dateref = new DateTimeReference("now"
class DateTimeReference {
function __construct($time) {
$this = new DateTime($time, new DateTimeZone("UTC"));
}
}
$date = new DateTime("now"); // in server time
$dateref = new DateTimeReference("now"); // in UTC
基本上,我想创建一个
DateTime
对象的“扩展”,但要设置时区。当然,这是一个错误,因为您无法重新分配$this
。我不想使用factory对象——有谁能推荐我如何实现这一点(或者使用什么模式,举个例子?)。可能是装饰图案?我认为这样做没有问题
class DateTimeReference extends DateTime {
function __construct($time, $timezone) {
parent::__construct($time);
$this->setTimeZone(new DateTimeZone($timezone));
}
}
$dateref = new DateTimeReference("now", "America/New_York");
您还可以通过以下方式选择时区:
class DateTimeReference extends DateTime {
function __construct($time, $timezone = "America/New_York") {
parent::__construct($time);
$this->setTimeZone(new DateTimeZone($timezone));
}
}
$dateref = new DateTimeReference("now");
此外,您只需将新的DateTimeZone对象传递给DateTime的构造函数:
$dateref = new DateTime("now", new DateTimeZone("America/New_York"));
请参见示例部分:您能做到以下几点吗:
date_default_timezone_set('UTC');
取决于你的应用程序还能做什么,但如果你能做到这一点,这是最简单的:-)我不知道这是否符合你想要使用的模式,但它应该可以工作
class DateTimeReference extends DateTime {
function __construct(string $time = "now" , DateTimeZone $timezone = NULL ) {
parent::__construct($time, new DateTimeZone("UTC"));
}
}
或者,如果您希望用户能够覆盖时区,但如果未设置,则默认为UTC:
class DateTimeReference extends DateTime {
function __construct(string $time = "now" , DateTimeZone $timezone = NULL ) {
parent::__construct($time, is_null($timezone) ? new DateTimeZone("UTC") : $timezone );
}
}
这不起作用,因为您正在重新定义构造函数。但是我不想每次都将
DateTimeZone
对象传递给构造函数,这就是DateTimeReference
的点。在第一个示例中,您不传递DateTimeZone对象,而是传递定义要使用的时区的字符串。如果要使时区可选,可以设置默认值。我将编辑我的答案以反映这一点。您可以。如果您这样做,DateTime对象的默认时区现在将是UTC,这基本上就是您的代码试图实现的。