Psy*_*che 31 php datetime date
我怎样才能得到当周的星期一和星期五的日期?
我有以下代码,但如果当天是星期日或星期六,则会失败.
$current_day = date("N");
$days_to_friday = 5 - $current_day;
$days_from_monday = $current_day - 1;
$monday = date("Y-m-d", strtotime("- {$days_from_monday} Days"));
$friday = date("Y-m-d", strtotime("+ {$days_to_friday} Days"));
Run Code Online (Sandbox Code Playgroud)
Sal*_*n A 64
这些strtotime输入工作得非常好:
strtotime( "next monday" );
strtotime( "previous monday" );
strtotime( "today" );
strtotime( "next friday" );
strtotime( "previous friday" );
Run Code Online (Sandbox Code Playgroud)
您需要做的就是将逻辑包装在一些if语句中.
GDY*_*GDY 60
最佳解决方案是:
$monday = date( 'Y-m-d', strtotime( 'monday this week' ) );
$friday = date( 'Y-m-d', strtotime( 'friday this week' ) );
Run Code Online (Sandbox Code Playgroud)
vas*_*ite 11
这个问题需要一个DateTime答案: -
/**
* @param String $day
* @return DateTime
*/
function getDay($day)
{
$days = ['Monday' => 1, 'Tuesday' => 2, 'Wednesday' => 3, 'Thursday' => 4, 'Friday' => 5, 'Saturday' => 6, 'Sunday' => 7];
$today = new \DateTime();
$today->setISODate((int)$today->format('o'), (int)$today->format('W'), $days[ucfirst($day)]);
return $today;
}
Run Code Online (Sandbox Code Playgroud)
用法:
var_dump(getDay('Monday')->format('l dS F Y'));
var_dump(getDay('Friday')->format('l dS F Y'));
Run Code Online (Sandbox Code Playgroud)
输出:
string 'Monday 30th September 2013' (length=26)
string 'Friday 04th October 2013' (length=24)
Run Code Online (Sandbox Code Playgroud)