我有以下代码:
$posted_on = new DateTime($date_started);
$today = new DateTime('today');
$yesterday = new DateTime('yesterday');
$myFormat = 'format(\'Y-m-d\')';
if($posted_on->{$myFormat} == $today->{$myFormat}) {
$post_date = 'Today';
}
elseif($posted_on->{$myFormat} == $yesterday->{$myFormat}) {
$post_date = 'Yesterday';
}
else{
$post_date = $posted_on->format('F jS, Y');
}
echo 'Started '.$post_date;
正如你所看到我试图多次使用“格式('Ym-d'),并且不想在多个地方输入它,所以我试图简单地将它放在一个变量中并使用它。但是,我收到通知:消息:未定义的属性:DateTime :: $ format('Y-m-d')
这样做的正确方法是什么?
答案 0 :(得分:5)
$myFormat = 'Y-m-d';
...
$today->format($myFormat);
...
答案 1 :(得分:4)
不,但你可以讨论这个功能:
$myFormat = function($obj) {return $obj->format("Y-m-d");};
if( $myFormat($posted_on) == $myFormat($today))
或者更干净:
class MyDateTime extends DateTime {
public function format($fmt="Y-m-d") {
return parent::format($fmt);
}
}
$posted_on = new MyDateTime($date_started);
$today = new MyDateTime("today");
$yesterday = new MyDateTime("yesterday");
if( $posted_on->format() == $today->format()) {...
答案 2 :(得分:1)
$posted_on = new DateTime($date_started);
$today = new DateTime('today');
$yesterday = new DateTime('yesterday');
$myFormat = 'Y-m-d';
if($posted_on->format($myFormat) == $today->format($myFormat)) {
$post_date = 'Today';
}
elseif($posted_on->format($myFormat) == $yesterday->($myFormat)) {
$post_date = 'Yesterday';
}
else{
$post_date = $posted_on->format('F jS, Y');
}
echo 'Started '.$post_date;
这是你能做的最好的事情。我会把格式放在一个常量或配置文件中,但是w / e。你想要做的事情是可能的,但是当我读到它时,我真的开始哭了是非常可怕的。
同样在这种情况下我会做这样的事情
$interval = $posted_on->diff(new DateTime('today'));
$postAge = $interval->format('%d'); // Seems to be the best out of many horrible options
if($postAge == 1)
{
$post_date = 'Today';
}
else if($postAge == 2)
{
$post_date = 'Yesterday';
}
else
{
$post_date = $posted_on->format('F jS, Y');
}