我想用
strtotime("last Monday")
。
问题是,如果今天是星期一,它会返回什么? 它似乎正在返回上周星期一的日期。在这种情况下我怎样才能让它返回今天的日期?
如果您阅读手册,其中有一个很好的示例,它准确地描述了您想要执行的操作https://www.php.net/manual/en/datetime.formats.php#datetime.formats.relative
strtotime('Monday this week');
更新: 在较新版本的 PHP 中似乎引入了一个 bug,其中
this week
在周日运行时返回错误的星期。您可以在这里对该错误进行投票:https://bugs.php.net/bug.php?id=63740
更新 2: 截至 2016 年 5 月 18 日,此问题已在 PHP 5.6.22、PHP 7.0.7 和 PHP 7.1-dev 中修复(并希望在后续版本中保持修复),如下所示:https://bugs .php.net/bug.php?id=63740#1463570467
在这种情况下我怎样才能让它返回今天的日期?
伪代码:
if (today == monday)
return today;
else
return strtotime(...);
顺便说一句,这个技巧也可以工作:
strtotime('last monday', strtotime('tomorrow'));
如果今天是星期一,strtotime("last Monday") 将返回 7 天前的日期。为什么不检查今天是否是星期一,如果是,则返回今天的日期,如果不是,则返回上周的日期?
这将是一个万无一失的方法。
if (date('N', time()) == 1) return date('Y-m-d');
else return date('Y-m-d', strtotime('last Monday'));
正如在之前的答案中正确概述的那样,这个技巧是有效的,但在PHP 5.6.22
、
PHP 7.0.7
和PHP 7.1-dev
之前也有警告:
strtotime('last monday', strtotime('tomorrow'));
// or this one, which is shorter, but was buggy:
strtotime('Monday this week');
DateTime
类的对象,解决方案如下:
(new \DateTime())->modify('tomorrow')->modify('previous monday')->format('Y-m-d');
或更短的符号:
\DateTime('Monday this week')
要小心,因为如果你在 SQL 上做同样的事情,你不需要在 mysql 中添加“明天”来使用任何这些技巧。解决方案如下所示:
SELECT DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY) as last_monday;
迟到的答案,但我想我会发布这个答案(实际上来自另一个不同但相关的问题)。它处理问题中的场景:
function last_monday($date) {
if (!is_numeric($date))
$date = strtotime($date);
if (date('w', $date) == 1)
return $date;
else
return strtotime(
'last monday',
$date
);
}
echo date('m/d/y', last_monday('8/14/2012')); // 8/13/2012 (tuesday gives us the previous monday)
echo date('m/d/y', last_monday('8/13/2012')); // 8/13/2012 (monday throws back that day)
echo date('m/d/y', last_monday('8/12/2012')); // 8/06/2012 (sunday goes to previous week)
尝试一下:http://codepad.org/rDAI4Scr
...或者周日返回第二天(星期一)而不是前一周的变体,只需添加一行:
elseif (date('w', $date) == 0)
return strtotime(
'next monday',
$date
);
尝试一下:http://codepad.org/S2NhrU2Z
您可以向其传递时间戳或字符串,您将得到一个时间戳
文档
这可能很有用,具体取决于您使用它的用途。由于一秒钟的模糊性可以满足我的要求,因此我使用:
date( 'Y-m-d 23:59:59', strtotime( 'last sunday' ))
获取最近星期一的午夜(如果今天是星期一,则为今天)。
我的做法:
date_default_timezone_set('Europe/Berlin');
function givedate($weekday, $time) {
$now = time();
$last = strtotime("$weekday this week $time");
$next = strtotime("next $weekday $time");
if($now > $last) {
$date = date("d.m.Y - H:i",$next);
}
else {
$date = date("d.m.Y - H:i",$last);
}
return $date;
}
echo givedate('Wednesday', '00:52');
或每月
function givedate_monthly($weekday, $time) {
$now = time();
$last = strtotime("first $weekday of this month $time");
$next = strtotime("first $weekday of next month $time");
if($now > $last) {
$date = date("d.m.Y - H:i",$next);
}
else {
$date = date("d.m.Y - H:i",$last);
}
return $date;
}
echo givedate_monthly('Wednesday', '01:50');
$monday = strtotime('Monday last week');
$sunday = strtotime('+6 days', $monday);