Issue with getting week starting from sunday

2019-02-19 20:41发布

问题:

Following is the function which I have created for getting sunday as a starting day of a week,


function getCurrentIntervalOfWeek($liveratetime) {
    // get start of each week.
    $dayofweek = date('w', $liveratetime);
    $getdate = date('Y-m-d', $liveratetime);
    $createstart = strtotime('last Sunday', $getdate);
    $weekstart = ($dayofweek == 0) ? $liveratetime : $createstart;
    // get the current time interval for a week, i.e. Sunday 00:00:00 UTC
    $currentInterval = mktime(0,0,0, date('m', $weekstart), date('d', $weekstart), date('Y', $weekstart));
    return $currentInterval;
}

Here liveratetime is the epoch time of any day in a week. Basically this function takes the liveratetime and looks for last sunday so as to get the current interval for that perticulat liveratetime epoch.

but the issue here is that, whenever I try to get current interval from this for certain liveratetime the

$createstart = strtotime('last Sunday', $getdate);
gives me
-345600
. And I am not getting why? can anyone please share a light on this.

This usually happens on the past dates like

2007-10-02

回答1:

Strtotime's second parameter is a TIMESTAMP, not a string representation of a date. Try:

$createstart = strtotime('last Sunday', $liveratetime);

It gives you -345600, because when $getdate, which is Y-m-d, is parsed as an int results in 0 - the epoch time. So, last sunday from epoch time is the result...



回答2:

You might want to try this function, it will return an array of dates, starting on sunday, based on the date it is provided.

function get_week_dates( $date )
{
// the return array
$dates = array();

$time = strtotime($date);
$start = strtotime('last Sunday', $time);

$dates[] = date( 'Y-m-d', $start );

// calculate the rest of the times
for( $i = 1; $i < 7; $i++ )
{
    $dates[] = date( 'Y-m-d' , ( $start + ( $i * ( 60 * 60 * 24 ) ) ) );
}

return $dates;
}

usage

get_week_dates( '2011-03-21' );

will return

array
  0 => string '2011-03-20' (length=10)
  1 => string '2011-03-21' (length=10)
  2 => string '2011-03-22' (length=10)
  3 => string '2011-03-23' (length=10)
  4 => string '2011-03-24' (length=10)
  5 => string '2011-03-25' (length=10)
  6 => string '2011-03-26' (length=10)


回答3:

I was looking for a solution for this problem and after some researching and trying, it seemed like this works... although I still need to test is on next sunday to see if it really did.. anyway here is the code:

$week_start = new DateTime();
$week = strftime("%U");  //this gets you the week number starting Sunday
$week_start->setISODate(2012,$week,0); //return the first day of the week with offset 0
echo $week_start -> format('d-M-Y'); //and just prints with formatting 


标签: php strtotime