如何获取php中上周(星期二或其他日期)的日期? [英] how to get the date of last week's (tuesday or any other day) in php?

查看:407
本文介绍了如何获取php中上周(星期二或其他日期)的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想做的是:



如果今天是星期二feb 2 2009,我将如何知道上周星期二的日期?使用相同的代码2天后,我会发现上周星期二的同一天,当前的日期是星期三,feb 4 2009。

解决方案

我知道已经有一个公认的答案,但是它并不符合被要求的第二个要求。在上述情况下,如果在星期三使用,strtotime将会产生昨天。所以,只要确切地,你仍然需要检查:

  $ tuesday = strtotime('last Tuesday'); 
//检查我们是否需要再次返回一个星期
$ tuesday = date('W',$ tuesday)== date('W')? $ tuesday-7 * 86400:$ tuesday;






正如davil在评论中指出的,我的一个快速射击。由于夏令时,上述计算将每年关闭一次。足够好的解决方案是:

  $ tuesday = date('W',$ tuesday)== date ')? $ tuesday-7 * 86400 + 7200:$ tuesday; 

如果您需要时间为0:00h,则需要额外付出努力。


I think its possible but i cant come up with the right algorithm for it.

What i wanted to do was:

If today is monday feb 2 2009, how would i know the date of last week's tuesday? Using that same code 2 days after, i would find the same date of last week's tuesday with the current date being wednesday, feb 4 2009.

解决方案

I know there is an accepted answer already, but imho it does not meet the second requirement that was asked for. In the above case, strtotime would yield yesterday if used on a wednesday. So, just to be exact you would still need to check for this:

$tuesday = strtotime('last Tuesday');
// check if we need to go back in time one more week
$tuesday = date('W', $tuesday)==date('W') ? $tuesday-7*86400 : $tuesday;


As davil pointed out in his comment, this was kind of a quick-shot of mine. The above calculation will be off by one once a year due to daylight saving time. The good-enough solution would be:

$tuesday = date('W', $tuesday)==date('W') ? $tuesday-7*86400+7200 : $tuesday;

If you need the time to be 0:00h, you'll need some extra effort of course.

这篇关于如何获取php中上周(星期二或其他日期)的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆