2010-12-14 59 views
13

可能重复:
Get first day of week in PHP?寻找一周的第一天通过PHP

嗨,

我想找到当前周和最后一周的第一和最后日期。 同样,我想查找当前月份和上个月的第一个和最后一个日期。

这必须在PHP中完成。请帮忙。

+0

参见:http://stackoverflow.com/questions/1897727/get-first php中的周日期 – 2010-12-14 13:41:41

+3

*(参考)* [PHP中的相对日期格式](http://de2.php.net/manual/en/datetime.formats.relative.php) – Gordon 2010-12-14 13:46:25

回答

42

strtotime是相当强大的与relative time formats

strtotime('monday this week'); 
strtotime('sunday this week'); 
strtotime('monday last week'); 
strtotime('sunday last week'); 

(这仅适用于PHP 5.3+)

strtotime('first day of this month'); 
strtotime('last day of this month'); 
strtotime('first day of last month'); 
strtotime('last day of last month'); 

为了获得每月的第一个和最后一个日期在PHP < 5.3中,您可以使用组合mktimedatedate('t')给出该月的天数):

mktime(0,0,0,null, 1); // gives first day of current month 
mktime(0,0,0,null, date('t')); // gives last day of current month 

$lastMonth = strtotime('last month'); 
mktime(0,0,0,date('n', $lastMonth), 1); // gives first day of last month 
mktime(0,0,0,date('n', $lastMonth), date('t', $lastMonth); // gives last day of last month 

如果你只是想呈现一个字符串,那么你不需要mktime

date('Y-m-1'); // first day current month 
date('Y-m-t'); // last day current month 
date('Y-m-1', strtotime('last month')); // first day last month 
date('Y-m-t', strtotime('last month')); // last day last month 
+0

您提供了出色的解决方案但不幸的是,这只适用于PHP5.3而不是5.2。我有PHP 5.2.14。这没有奏效! – 2010-12-14 14:11:19

+1

@ user365870:的确,它没有记录在任何地方,我只是在页面的评论中阅读它......无论如何,请参阅我的更新答案。 – 2010-12-14 14:28:08

+0

谢谢!这工作完美。非常感谢。 – 2010-12-14 16:08:43

3

这里是一个函数的一周的第一天和最后一天:

function week_start_date($wk_num, $yr, $first = 1, $format = 'F d, Y') 
{ 
    $wk_ts = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101')); 
    $mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts); 
    return date($format, $mon_ts); 
} 

$sStartDate = week_start_date($week_number, $year); 
$sEndDate = date('F d, Y', strtotime('+6 days', strtotime($sStartDate))); 

大概可以适应做一个月为好,但我希望得到我的答案! :)

+0

我实际找到他自己引用Googling的论坛帖子,谢谢:) ......甚至没有看到他的答案,从其他的stackoverflow线程... – prilldev 2010-12-14 14:04:45

+0

好吧,然后我撤回我的评论:) – 2010-12-14 14:09:45

+0

这也适用于我。谢谢 – 2010-12-14 16:09:03