Reputation:
How can i get a Date of Monday
and Date of Sunday
if i have specific Date in mysql
DATETIME
format ?
i am trying to get the week's first day's date and last day's date in which the given date falls.
i have date '2016-06-05' its in 'Y-m-d'
and i am trying it like this way.
<?php
$date = '2016-06-05';
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n";
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n";
?>
but its giving
2016-06-06
2016-06-12
which is wrong week, it should give
2016-05-30
2016-06-05
i even tried like this way.
$date = '2016-06-05';
echo date("Y-m-d", strtotime('monday', strtotime('this week', strtotime($date)))), "\n";
echo date("Y-m-d", strtotime('sunday', strtotime('this week', strtotime($date)))), "\n";
OR
$date = '2016-06-05';
echo date("Y-m-d", strtotime('monday', strtotime($date))), "\n";
echo date("Y-m-d", strtotime('sunday', strtotime($date))), "\n";
using PHP 5.3
what am i missing here ?
UPDATE:
i came up with this, this is giving expected output.
function get_monday_sunday($date){
$dates_array = array();
if(date('N', strtotime($date)) == 7){
$dates_array['monday'] = date("Y-m-d", strtotime('Monday last week', strtotime($date)));
$dates_array['sunday'] = date("Y-m-d", strtotime('Sunday last week', strtotime($date)));
}else{
$dates_array['monday'] = date("Y-m-d", strtotime('Monday this week', strtotime($date)));
$dates_array['sunday'] = date("Y-m-d", strtotime('Sunday this week', strtotime($date)));
}
return $dates_array;
}
$date = '2016-06-05'
print_r(get_monday_sunday($date));
looks like when the day is last day of week, then next week starts over, i.e. php week start is sunday i guess.
Upvotes: 0
Views: 4515
Reputation: 14308
In every single php project I make, I always include the Carbon package. It extends the DateTime class and adds some very nice functionality that makes working with dates a lot easier.
If you would take my suggestion, your code would look something like this:
$date = Carbon::parse($dateStringFromDb);
echo $date->startOfWeek()->format('Y-m-d'); // monday
echo $date->endOfWeek()->format('Y-m-d'); // sunday
And that is really all there is to it. This is what I call "self commenting code"! I bet you're actually going to enjoy program with dates ;-)
Upvotes: 3