PHP - 从变量创建DateTime

时间:2015-10-30 07:49:22

标签: php datetime

我有这样的变量:

$dateStr = "first day of January ' . (new DateTime())->format('Y') . ' 23:59:59";

现在我想从这里创建一个\DateTime ......所以我这样想:

$date = new \DateTime('\'' . $dateStr .'\'');

但它给出了错误......

Exception: DateTime::__construct(): Failed to parse time string ('first day of January ' . (new DateTime())->format('Y') . ' 23:59:59') at position 0 ('): Unexpected character

我的代码: $ dateStr =“1月的第一天”。(新的DateTime()) - >格式('Y')。'23:59:59“;

/ *在使用时可以正常工作* /

$dateStr = "first day of January ' . (new DateTime())->format('Y') . ' 23:59:59";

$date2 = new DateTime('first day of January ' . (new DateTime())->format('Y') . ' 23:59:59');
echo $date2->format('Y-m-d H:i:s') . PHP_EOL . PHP_EOL;

/* fails when used like this */
$date = new DateTime('\'' . $dateStr . '\'');
echo $date->format('Y-m-d H:i:s');

工作小提琴:http://sandbox.onlinephpfunctions.com/code/829da64825758f35e26087b2f9a81d93421b9941

2 个答案:

答案 0 :(得分:1)

试试这个: -

$dateStr = "first day of January " . (new DateTime())->format('Y') . " 23:59:59";
/* works when used like this */
$date2 = new DateTime('first day of January ' . (new DateTime())->format('Y') . ' 23:59:59');
echo $date2->format('Y-m-d H:i:s') . PHP_EOL . PHP_EOL;
/* fails when used like this */
$date = new \DateTime($dateStr);
echo $date->format('Y-m-d H:i:s');

答案 1 :(得分:-1)

如果那是您必须使用的字符串,则应将其评估为PHP代码。

$date = new DateTime(eval('return \'' . $dateStr . '\';'));
echo $date->format('Y-m-d H:i:s');

然而,强烈建议不要使用eval()并将代码显示在字符串变量或数据库中,并将其视为有害做法。