在PHP中获取给定周的开始和结束日期
我正在尝试以星期日为开始日期来获取星期范围,参考日期,例如 $ date
,但我似乎无法想象
I'm trying to get the week range using Sunday as the start date, and a reference date, say $date
, but I just can't seem to figure it out.
例如,如果我的日期为2009-05-01,我将获得2009-04-26和2009-05-02。 2009-05-10将产生2009-05-10和2009-05-16。我现在的代码看起来像这样(我不记得我在哪里解除了,因为我忘了在我的评论中放下url):
For example, if I had $date as 2009-05-01, I would get 2009-04-26 and 2009-05-02. 2009-05-10 would yield 2009-05-10 and 2009-05-16. My current code looks like this (I can't remember where I lifted it from, as I forgot to put down the url in my comments):
function x_week_range(&$start_date, &$end_date, $date)
{
$start_date = '';
$end_date = '';
$week = date('W', strtotime($date));
$week = $week;
$start_date = $date;
$i = 0;
while(date('W', strtotime("-$i day")) >= $week) {
$start_date = date('Y-m-d', strtotime("-$i day"));
$i++;
}
list($yr, $mo, $da) = explode('-', $start_date);
$end_date = date('Y-m-d', mktime(0, 0, 0, $mo, $da + 6, $yr));
}
我意识到这一切都是在当前日期添加了7天。你会怎么做?
I realized all it did was add 7 days to the current date. How would you do this?
我会采取PHP的优势 strtotime awesomeness:
I would take advantange of PHP's strtotime awesomeness:
function x_week_range(&$start_date, &$end_date, $date) {
$ts = strtotime($date);
$start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
$start_date = date('Y-m-d', $start);
$end_date = date('Y-m-d', strtotime('next saturday', $start));
}
根据您提供的数据进行测试,它可以工作。我不是特别喜欢你所参与的整个事情。如果这是我的功能,我会有这样的:
Tested on the data you provided and it works. I don't particularly like the whole reference thing you have going on, though. If this was my function, I'd have it be like this:
function x_week_range($date) {
$ts = strtotime($date);
$start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
return array(date('Y-m-d', $start),
date('Y-m-d', strtotime('next saturday', $start)));
}
并像下面这样调用:
list($start_date, $end_date) = x_week_range('2009-05-10');
我不是像这样做数学的粉丝。日期是棘手的,我更喜欢PHP计算出来。
I'm not a big fan of doing math for things like this. Dates are tricky and I prefer to have PHP figure it out.