我正在创建一个新的Date期间作为数组。我循环浏览日期,并试图将Day值作为字符串获取
<?php
$period = new DatePeriod(
new DateTime('27-02-2019'),
new DateInterval('P1D'),
new DateTime('03-03-2019')
);
foreach( $period as $date) { $array[] = $date->format('d-m-y');
$newDate = $date->format('d/m/Y'); // for example
echo "The date is " .$newDate." ";
$timestamp = strtotime($newDate);
$day = date('l', $timestamp);
echo "The day is ".$day." \n"; ?>
<br>
<?}?>
根据我的回声,我得到了正确的日期,但它给出了错误的日期。
答案 0 :(得分:2)
通过将DateTime()
与strtotime()
结合使用,您在处理日期时遇到了常见错误。通过尝试使用dd / mm / yyyy格式转换日期,假定您使用的美国日期格式是mm / dd / yyyy,这是不正确的。因此28/02/2019
变成了The second day of the 28th month in the year 2019
,这不是您想要的。
通过完全使用DateTime()
并避免不必要的格式转换,可以完全避免这种情况。甚至更少的代码!
<?php
$period = new DatePeriod(
new DateTime('27-02-2019'),
new DateInterval('P1D'),
new DateTime('03-03-2019')
);
foreach( $period as $date) { $array[] = $date->format('d-m-y');
$newDate = $date->format('d/m/Y'); // for example
echo "The date is " .$newDate." ";
$day = $date->format('l');
echo "The day is ".$day." \n"; ?>
<br>
<?}?>
输出:
The date is 27/02/2019 The day is Wednesday
The date is 28/02/2019 The day is Thursday
The date is 01/03/2019 The day is Friday
The date is 02/03/2019 The day is Saturday