我正在开发一个PHP应用程序,我需要使用日期和工作日的数字表示。
我试过以下方法:
$today = date("Y-m-d");
$number = date('N', strtotime($today));
echo "Today: " . $today . " weekday: " . $number . "<br>";
$today = strtotime($today);
$tomorrow = strtotime($today);
$tomorrow = strtotime("+1 day", $today);
$number2 = date('N', strtotime($tomorrow));
echo "Tomorrow: " . date('Y-m-d', $tomorrow) . " weekday: " . $number2 . "<br>";
输出Today: 2016-11-11 weekday: 5
Tomorrow: 2016-11-12 weekday: 4
这是不对的,因为明天的工作日应该是6而不是4。
有人能帮我一下吗?使用DateTime
将提供一个简单的解决方案
<?php
$date = new DateTime();
echo 'Today: '.$date->format( 'Y-m-d' ) .' weekday '. $date->format( 'N' )."'n";
$date->modify( '+1 days' );
echo 'Tomorrow: '.$date->format( 'Y-m-d' ) .' weekday '. $date->format( 'N' )."'n";
输出Today: 2016-11-11 weekday 5
Tomorrow: 2016-11-12 weekday 6
然而,日期略有不同,N表示工作日的数字,如您所见,星期五(今天)显示为5。这样的话,星期一是1,星期天是7。
如果你看下面的例子,你应该得到相同的结果
echo date( 'N' );
输出5
日期格式- http://php.net/manual/en/function.date.php
你的代码中有一点错误,下面是工作的代码:
$today = date("Y-m-d");
$number = date('N', strtotime($today));
echo "Today: " . $today . " weekday: " . $number . "<br>";
$today = strtotime($today);
$tomorrow = strtotime($today);
$tomorrow = strtotime("+1 day", $today);
$number2 = date('N', $tomorrow);
echo "Tomorrow: " . date('Y-m-d', $tomorrow) . " weekday: " . $number2 . "<br>";
DateTime是PHP中处理日期的面向对象方法。我发现它工作起来流畅多了。除此之外,它看起来好多了。
// Create a new instance
$now = new DateTime();
echo $now->format('N');
// Next day
$now->modify('+1 day');
echo $now->format('N');
资源- DateTime manual - PHP.net
你几乎说对了,但还不完全对。为什么在$number2
上使用strtotime
?把它改为$number2 = date('N', $tomorrow);
,它将工作