WMomesso
WMomesso

Reputation: 264

Get first/last day of week in php?

With get the date of the first day of the week and last day of the week in php, first day Monday and the last day Friday, for example I have the date 2017-05-23 and I want to know the Monday one 2017-05-22 and the last one that would be 2017-05-26

date now = '2017-05-23'
first day of week = '2017-05-22' (Monday)
last day of week = '2017-05-26' (Friday)

Can I do this using date?

Upvotes: 5

Views: 15572

Answers (4)

alanlittle
alanlittle

Reputation: 470

Something like this:

<?php
date_default_timezone_set("Asia/Kolkata");
$today = date("Y-m-d");
$mon = new DateTime($today);
$sun = new DateTime($today);
$mon->modify('last Monday');
$sun->modify('next Sunday');
var_dump($mon);
var_dump($sun);
$first_day_of_week = $mon->format("Y-m-d");
$last_day_of_week = $sun->format("Y-m-d");

Upvotes: 10

WMomesso
WMomesso

Reputation: 264

My solve,

$datenow = date('Y-m-d');// date now
$mon = new DateTime($datenow);
$fri = new DateTime($datenow);
$mon->modify('Last Monday');
$fri->modify('Next Friday');

using echo

echo 'Monday: '.$mon->format('Y-m-d').'<br>';
echo 'Friday: '.$fri->format('Y-m-d').'<br>';

using var_dump()

var_dump($mon);
var_dump($fri);

Upvotes: 0

George Peter
George Peter

Reputation: 69

$the_date = '2017-05-23';
$the_day_of_week = date("w",strtotime($the_date)); //sunday is 0

$first_day_of_week = date("Y-m-d",strtotime( $the_date )-60*60*24*($the_day_of_week)+60*60*24*1 );
$last_day_of_week = date("Y-m-d",strtotime($first_day_of_week)+60*60*24*4 );

echo $first_day_of_week;
echo "~";
echo $last_day_of_week;

Upvotes: 1

Omis Brown
Omis Brown

Reputation: 199

there is a solution but I'm not sure if you will accept it like this

$First_date = date_create('this week')->format('Y-m-d H:i:s');
$Last_date = date_create('this week +4 days')->format('Y-m-d H:i:s');
echo $First_date;
echo $Last_date;

Upvotes: 0

Related Questions