How to Find the Date of a Day of the Week from a Date Using PHP

How to find the date of a day of the week from a date using PHP?

I think this is what you want.

$dayofweek = date('w', strtotime($date));
$result = date('Y-m-d', strtotime(($day - $dayofweek).' day', strtotime($date)));

Get weekday by date

Try like this way,

<?php
$date = DateTime::createFromFormat('Y-m-d', '2018-06-21');
echo $date->format('l'); # l for full week day name
?>

Ref.: http://php.net/manual/en/datetime.createfromformat.php

Demo: https://eval.in/1025956

How to get the day of the week in DateTime?

You can use format() function

$today->format('l') //Sunday through Saturday
$today->format('w') //0 (for Sunday) through 6 (for Saturday)

Get whole week date starting from sunday to saturday from given date

From source,

Here is the snippet you are looking for,

// set current date
$date = '01/03/2018';
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow - 1;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset*86400;
// loop from Monday till Sunday
for ($i = 0; $i < 7; $i++, $ts += 86400){
print date("m/d/Y l", $ts) . "\n";
}

Here is working demo.

If you need normal standard format code,

Here is your snippet,

// set current date
$date = '2018-01-03';
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow - 1;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset * 86400;
// loop from Monday till Sunday
for ($i = 0; $i < 7; $i++, $ts += 86400) {
print date("Y-m-d l", $ts) . "\n";
}

Here is working demo.

EDIT

As per your requirement, now week will start from sunday to saturday

<?php
// set current date
$date = '2018-01-03';
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Sunday
$dow = date('w', $ts);
$offset = $dow;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Sunday
$ts = $ts - $offset * 86400;
// loop from Sunday till Saturday
for ($i = 0; $i < 7; $i++, $ts += 86400) {
print date("Y-m-d l", $ts) . "\n";
}

Convert date to day name e.g. Mon, Tue, Wed

This is what happens when you store your dates and times in a non-standard format. Working with them become problematic.

$datetime = DateTime::createFromFormat('YmdHi', '201308131830');
echo $datetime->format('D');

See it in action



Related Topics



Leave a reply



Submit