PHP-从变量创建DateTime


PHP - create DateTime from variable

我有这样的变量:

$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="一月的第一天。(new 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

试试这个:-

$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');

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

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

然而,强烈反对使用eval()并将代码显示在字符串变量或数据库中,这被认为是一种有害的做法。