How to find day of week in php in a specific timezone - php

I am confused while using php to handle date/time.
What I am trying to do is this: When a user visits my page I am asking his timezone and then displaying the 'day of week' in his timezone.
I don't want to use the browser's day.
I want to do this calculation in php.
This is how I am trying to achieve it:
The timezone entered by user
Unix time stamp calculated by php time() function.
But I dont know how to proceed...
How would i get the 'day of week' in this timezone.

$dw = date( "w", $timestamp);
Where $dw will be 0 (for Sunday) through 6 (for Saturday) as you can see here:
http://www.php.net/manual/en/function.date.php

My solution is this:
$tempDate = '2012-07-10';
echo date('l', strtotime( $tempDate));
Output is: Tuesday
$tempDate = '2012-07-10';
echo date('D', strtotime( $tempDate));
Output is: Tue

I think this is the correct answer, just change Europe/Stockholm to the users time-zone.
$dateTime = new \DateTime(
'now',
new \DateTimeZone('Europe/Stockholm')
);
$day = $dateTime->format('N');
ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)
1 (for Monday) through 7 (for Sunday)
http://php.net/manual/en/function.date.php
For a list of supported time-zones, see
http://php.net/manual/en/timezones.php

Thanks a lot guys for your quick comments.
This is what i will be using now.
Posting the function here so that somebody may use it.
public function getDayOfWeek($pTimezone)
{
$userDateTimeZone = new DateTimeZone($pTimezone);
$UserDateTime = new DateTime("now", $userDateTimeZone);
$offsetSeconds = $UserDateTime->getOffset();
//echo $offsetSeconds;
return gmdate("l", time() + $offsetSeconds);
}
Report if you find any corrections.

Another quick way:
date_default_timezone_set($userTimezone);
echo date("l");

If you can get their timezone offset, you can just add it to the current timestamp and then use the gmdate function to get their local time.
// let's say they're in the timezone GMT+10
$theirOffset = 10; // $_GET['offset'] perhaps?
$offsetSeconds = $theirOffset * 3600;
echo gmdate("l", time() + $offsetSeconds);

$myTimezone = date_default_timezone_get();
date_default_timezone_set($userTimezone);
$userDay = date('l', $userTimestamp);
date_default_timezone_set($myTimezone);
This should work (didn't test it, so YMMV). It works by storing the script's current timezone, changing it to the one specified by the user, getting the day of the week from the date() function at the specified timestamp, and then setting the script's timezone back to what it was to begin with.
You might have some adventures with timezone identifiers, though.

"Day of Week" is actually something you can get directly from the php date() function with the format "l" or "N" respectively. Have a look at
the manual
edit: Sorry I didn't read the posts of Kalium properly, he already explained that. My bad.

Check date is monday or sunday before get last monday or last sunday
public function getWeek($date){
$date_stamp = strtotime(date('Y-m-d', strtotime($date)));
//check date is sunday or monday
$stamp = date('l', $date_stamp);
$timestamp = strtotime($date);
//start week
if(date('D', $timestamp) == 'Mon'){
$week_start = $date;
}else{
$week_start = date('Y-m-d', strtotime('Last Monday', $date_stamp));
}
//end week
if($stamp == 'Sunday'){
$week_end = $date;
}else{
$week_end = date('Y-m-d', strtotime('Next Sunday', $date_stamp));
}
return array($week_start, $week_end);
}

Based on one of the other solutions with a flag to switch between weeks starting on Sunday or Monday
function getWeekForDate($date, $weekStartSunday = false){
$timestamp = strtotime($date);
// Week starts on Sunday
if($weekStartSunday){
$start = (date("D", $timestamp) == 'Sun') ? date('Y-m-d', $timestamp) : date('Y-m-d', strtotime('Last Sunday', $timestamp));
$end = (date("D", $timestamp) == 'Sat') ? date('Y-m-d', $timestamp) : date('Y-m-d', strtotime('Next Saturday', $timestamp));
} else { // Week starts on Monday
$start = (date("D", $timestamp) == 'Mon') ? date('Y-m-d', $timestamp) : date('Y-m-d', strtotime('Last Monday', $timestamp));
$end = (date("D", $timestamp) == 'Sun') ? date('Y-m-d', $timestamp) : date('Y-m-d', strtotime('Next Sunday', $timestamp));
}
return array('start' => $start, 'end' => $end);
}

echo date('l', strtotime('today'));

Related

How to get Last sunday date in Bootstrap Datepicker?

I am using bootstrap Datepicker and I want to set the date for current/last Sunday.The code below is showing the content form $date to $date1.
if (!isset($_POST['new-date'])){
$date = date('Y-m-d H:i:s');// I want to set last/current sunday
date here.
$date1 = date("Y-m-d H:i:s", strtotime("$date +6 day"));
$d = explode(" ",$date);
$d1 = explode(" ",$date1);
} else {
$d[0] = $_POST['new-date'];
$d1[0] = date("Y-m-d", strtotime("$d[0] +6 day"));
}
$d[0] = $_POST['new-date'];
The ['new-date'] may be any day/date from the calendar but It should select the last Sunday of that particular week.
Your code seems to be written in PHP, rather than JavaScript, so I'm not sure how relevant the question title or tags are.
// Check if the day of the week is a Sunday. If yes, use today's date. If no, use last Sunday's date
$timestamp = date('N') == 7 ? strtotime('today') : strtotime('last sunday');
$date = date('Y-m-d H:i:s', $timestamp);
die($date);
Edit
You asked in the comments how you can find last Sunday for any given date.
$timestamp = strtotime($_POST['date'] ?? 'today');
$sunday = (date('N', $timestamp) == 7) ? $timestamp : strtotime('last sunday', $timestamp);
$date = date('Y-m-d H:i:s', $sunday);
die($date);

PHP - how to use $timestamp to check if today is Monday or 1st of the month?

I have been looking through examples online, and I am finding them a bit cryptic or overkill.
What I need to do is something like this:
$timestamp = time();
and then find out if the day is a Monday or a fist of the month?
I am sure it is possible, I am just not sure how to do that.
Actually, you don't need timestamp variable because:
Exerpt from date function of php.net:
Returns a string formatted according to the given format string using
the given integer timestamp or the current time if no timestamp is
given. In other words, timestamp is optional and defaults to the value
of time().
if(date('j', $timestamp) === '1')
echo "It is the first day of the month today\n";
if(date('D', $timestamp) === 'Mon')
echo "It is Monday today\n";
This should solve it:
$day = date('D');
$date = date('d')
if($day == Mon){
//Code for monday
}
if($date == 01){
//code for 1st fo the month
}
else{
//not the first, no money for you =/
}
This will grab.. Monday from mysql
$monday = 1; //tuesday= 2.. sunday = 7
AND $monday = (date_format(from_unixtime(your_date_column),'%w'))
OR days..
$day = 1; ///1st in month
AND $day = (date_format(from_unixtime(your_date_column),'%d'))
JUST TO KNOW
$date = date("d"); //1st?
$dayinweek = date("w"); //monday? //as a number in a week what you need more then just "Monday" I guess..
You can use: strtotime
$firstdaymonth = strtotime('first day this month');
Because $date can monday or sunday. Should be check it
public function getWeek($date){
$date_stamp = strtotime(date('Y-m-d', strtotime($date)));
//check date is sunday or monday
$stamp = date('l', $date_stamp);
if($stamp == 'Mon'){
$week_start = $date;
}else{
$week_start = date('Y-m-d', strtotime('Last Monday', $date_stamp));
}
if($stamp == 'Sunday'){
$week_end = $date;
}else{
$week_end = date('Y-m-d', strtotime('Next Sunday', $date_stamp));
}
return array($week_start, $week_end);
}
Since PHP >= 5.1 it is possible to use date('N'), which returns an ISO-8601 numeric representation of the day of the week, where 1 is Monday and 7 is Sunday.
So you can do
if(date('N', $timestamp) === '1' || date('j', $timestamp) === '1')) {
echo "Today it is Monday OR the first of the month";
}

PHP: Week starts on Monday, but "monday this week" on a Sunday gets Monday next week

Here's a summary of the issue: On Sundays, strtotime('this week') returns the start of next week.
In PHP, the week seems to start on Monday. But, on any day except Sunday, this code
echo date('Y-m-d', strtotime('monday this week', strtotime('last sunday')));
Outputs the date of this week's Monday, when it seems like it should be outputting last weeks Monday. It seems like, in this case, PHP is treating both Sunday and Monday as the the start of the week. It's now Monday, Dec 10, 2012, or 2012-12-10. date('Y-m-d', strtotime('sunday last week')) returns 2012-12-09 - yesterday.
Is this a bug, or am I missing something? It seems like a bug this obvious should be fairly well known, but I can't find anything about it. Is the only way to get the start of the week to use some special handling for Sundays?
$week_offset = (int) 'sunday' == date('l');
$week_start = strtotime("-$week_offset monday"); // 1 or 0 Mondays ago
As far as I can tell, this is a bug. I see no logical reason why strtotime('this week'); should return a future date. This is a pretty major bug. In my particular case, I had a leaderboard that showed the users with the most points since the beginning of the week. But on Sundays, it was empty because strtotime returned a timestamp for a future date. I was doubtful, because just I don't know how this could have gone unnoticed, but I couldn't find any other reports of this bug.
Thanks for all your time and help, folks.
This answer is late, but it's something that I've been struggling with. Every solution I've tried so far has malfunctioned for one reason or another. This is what I ended up with that worked for me. (though it may be look pretty, it at least works).
$thisMonday = strtotime('next Monday -1 week', strtotime('this sunday'));
Here is how you can get Monday of current week:
echo date("Y-m-d", strtotime(date('o-\\WW')));
It's not ideal but this is what I resorted to using:
if(date('N') == 7) {
$date = date('Y-m-d',strtotime('monday last week'));
} else {
$date = date('Y-m-d',strtotime('monday this week'));
}
I think the only problem with your coding is TimeZone.
Solution:
Set your own time Zone. Here is the example of my own time zone:
Example
date_default_timezone_set('Asia/Kolkata');
Set the above line before calling any time function.
Have a nice day.
I think instead of trying
echo date('Y-m-d', strtotime('monday this week', strtotime('last sunday')));
you should try
echo date('Y-m-d', strtotime('monday last week'));
Try this code
// set current date
$date = date("m/d/Y");
$ts = strtotime($date); // also $ts = time();
// find the year and the current week
$year = date('o', $ts);
$week = date('W', $ts);
// print week for the current date
$i = 1; // 1 denotes the first day of week
$ts = strtotime($year.'W'.$week.$i);
echo $day = date("l", $ts); // generate the name of day
echo "<br>";
echo $day = date("Y-m-d", $ts); // generate the date
You will get the the date of current week, whether you are on monday you will get the date of that monday.
If you want the most recent monday:
function mostRecentMonday(){
if(date("w") == 1){
return strtotime("midnight today");
} else {
return strtotime("last monday");
}
}
Easy to modify to use DateTime, or, to even specify a different date to use as the base.
Based on Bryant answer :
$first_week_date = date('d F Y', strtotime('next Monday -1 week', strtotime('this sunday')));
$last_week_date = date('d F Y', strtotime('next Monday -1 week + 6 days', strtotime('this sunday')));
This is for thos looking for a friendly solution that works with any day.
function getWeekStart($week_start_day = "Monday") {
$week_days = array("Sunday"=>0,"Monday"=>1,"Tuesday"=>2,"Wednesday"=>3,"Thursday"=>4,"Friday"=>5,"Saturday"=>6,);
if(!isset($week_days[$week_start_day])) {
return false;
} else {
$start_day = $week_days[$week_start_day];
$today = date("w");
$one_day = (60 * 60 * 24);
if($today < $start_day) {
$days_difference = 7 - ($start_day - $today);
} else {
$days_difference = ($today - $start_day);
}
$week_starts = strtotime(date("Y-m-d 00:00:00")) - ($one_day * $days_difference);
return $week_starts;
}
}
//Test: If today is Monday, it will return today's date
echo date("Y-m-d H:i:s", getWeekStart("Monday"));

php strtotime "last monday" if today is monday?

I want to use strtotime("last Monday").
The thing is, if today IS MONDAY, what does it return?
It seems to be returning the date for the monday of last week. How can I make it return today's date in that case?
If you read the manual, there is an great example that describes exactly what you want to do http://www.php.net/manual/en/datetime.formats.relative.php
strtotime('Monday this week');
Update: There appears to be a bug introduced in newer versions of PHP where this week returns the wrong week when ran on Sundays. You can vote on the bug here: https://bugs.php.net/bug.php?id=63740
Update 2: As of May 18th 2016, this has been fixed in PHP 5.6.22, PHP 7.0.7 and PHP 7.1-dev (and hopefully remains fixed in subsequent releases) as seen here: https://bugs.php.net/bug.php?id=63740#1463570467
How can I make it return today's date in that case?
pseudocode:
if (today == monday)
return today;
else
return strtotime(...);
Btw, this trick also could work:
strtotime('last monday', strtotime('tomorrow'));
If today is Monday, strtotime("last Monday") will return a date 7 days in the past. Why don't you just check if today is Monday and if yes, return today's date and if not, return last week?
That would be a foolproof way of doing this.
if (date('N', time()) == 1) return date('Y-m-d');
else return date('Y-m-d', strtotime('last Monday'));
http://us2.php.net/manual/en/function.date.php
As it was correctly outlined in the previous answer, this trick works, but also had caveats prior to PHP 5.6.22, PHP 7.0.7 and PHP 7.1-dev:
strtotime('last monday', strtotime('tomorrow'));
// or this one, which is shorter, but was buggy:
strtotime('Monday this week');
To those, who prefer the "Jedy-way", to work with objects of the DateTime class, the solution is next:
(new \DateTime())->modify('tomorrow')->modify('previous monday')->format('Y-m-d');
or even shorter notation:
\DateTime('Monday this week')
Be carefull, because if you do the same on SQL, you don't need to have any of these tricks in mysql with addition of "tomorrow". Here's how the solution will look:
SELECT DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY) as last_monday;
Late answer, but I thought I would post up this answer (which is actually from a different but related question). It handles the scenario in the question:
function last_monday($date) {
if (!is_numeric($date))
$date = strtotime($date);
if (date('w', $date) == 1)
return $date;
else
return strtotime(
'last monday',
$date
);
}
echo date('m/d/y', last_monday('8/14/2012')); // 8/13/2012 (tuesday gives us the previous monday)
echo date('m/d/y', last_monday('8/13/2012')); // 8/13/2012 (monday throws back that day)
echo date('m/d/y', last_monday('8/12/2012')); // 8/06/2012 (sunday goes to previous week)
try it: http://codepad.org/rDAI4Scr
... or a variation that has sunday return the following day (monday) rather than the previous week, simply add a line:
elseif (date('w', $date) == 0)
return strtotime(
'next monday',
$date
);
try it: http://codepad.org/S2NhrU2Z
You can pass it a timestamp or a string, you'll get back a timestamp
Documentation
strtotime - http://php.net/manual/en/function.strtotime.php
date - http://php.net/manual/en/function.date.php
Depending on exactly what you're using it for, this may be useful. Since one second's ambiguity is OK for my requirements, I use:
date( 'Y-m-d 23:59:59', strtotime( 'last sunday' ))
to get midnight on the most recent Monday (or today if today IS Monday).
My aproach:
date_default_timezone_set('Europe/Berlin');
function givedate($weekday, $time) {
$now = time();
$last = strtotime("$weekday this week $time");
$next = strtotime("next $weekday $time");
if($now > $last) {
$date = date("d.m.Y - H:i",$next);
}
else {
$date = date("d.m.Y - H:i",$last);
}
return $date;
}
echo givedate('Wednesday', '00:52');
Or monthly
function givedate_monthly($weekday, $time) {
$now = time();
$last = strtotime("first $weekday of this month $time");
$next = strtotime("first $weekday of next month $time");
if($now > $last) {
$date = date("d.m.Y - H:i",$next);
}
else {
$date = date("d.m.Y - H:i",$last);
}
return $date;
}
echo givedate_monthly('Wednesday', '01:50');
$monday = strtotime('Monday last week');
$sunday = strtotime('+6 days', $monday);

Get first day of week in PHP?

Given a date MM-dd-yyyy format, can someone help me get the first day of the week?
Here is what I am using...
$day = date('w');
$week_start = date('m-d-Y', strtotime('-'.$day.' days'));
$week_end = date('m-d-Y', strtotime('+'.(6-$day).' days'));
$day contains a number from 0 to 6 representing the day of the week (Sunday = 0, Monday = 1, etc.).
$week_start contains the date for Sunday of the current week as mm-dd-yyyy.
$week_end contains the date for the Saturday of the current week as mm-dd-yyyy.
Very simple to use strtotime function:
echo date("Y-m-d", strtotime('monday this week')), "\n";
echo date("Y-m-d", strtotime('sunday this week')), "\n";
It differs a bit across PHP versions:
Output for 5.3.0 - 5.6.6, php7#20140507 - 20150301, hhvm-3.3.1 - 3.5.1
2015-03-16
2015-03-22
Output for 4.3.5 - 5.2.17
2015-03-23
2015-03-22
Output for 4.3.0 - 4.3.4
2015-03-30
2015-03-29
Comparing at Edge-Cases
Relative descriptions like this week have their own context. The following shows the output for this week monday and sunday when it's a monday or a sunday:
$date = '2015-03-16'; // monday
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n";
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n";
$date = '2015-03-22'; // sunday
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n";
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n";
Againt it differs a bit across PHP versions:
Output for 5.3.0 - 5.6.6, php7#20140507 - 20150301, hhvm-3.3.1 - 3.5.1
2015-03-16
2015-03-22
2015-03-23
2015-03-29
Output for 4.3.5 - 5.0.5, 5.2.0 - 5.2.17
2015-03-16
2015-03-22
2015-03-23
2015-03-22
Output for 5.1.0 - 5.1.6
2015-03-23
2015-03-22
2015-03-23
2015-03-29
Output for 4.3.0 - 4.3.4
2015-03-23
2015-03-29
2015-03-30
2015-03-29
strtotime('this week', time());
Replace time(). Next sunday/last monday methods won't work when the current day is sunday/monday.
Keep it simple :
<?php
$dateTime = new \DateTime('2020-04-01');
$monday = clone $dateTime->modify(('Sunday' == $dateTime->format('l')) ? 'Monday last week' : 'Monday this week');
$sunday = clone $dateTime->modify('Sunday this week');
?>
Source : PHP manual
NB: as some user commented the $dateTime value will be modified.
$givenday = date("w", mktime(0, 0, 0, MM, dd, yyyy));
This gives you the day of the week of the given date itself where 0 = Sunday and 6 = Saturday. From there you can simply calculate backwards to the day you want.
This question needs a good DateTime answer:-
function firstDayOfWeek($date)
{
$day = DateTime::createFromFormat('m-d-Y', $date);
$day->setISODate((int)$day->format('o'), (int)$day->format('W'), 1);
return $day->format('m-d-Y');
}
var_dump(firstDayOfWeek('06-13-2013'));
Output:-
string '06-10-2013' (length=10)
This will deal with year boundaries and leap years.
EDIT: the below link is no longer running on the version of PHP stated. It is running on PHP 5.6 which improves the reliability of strtotime, but isn't perfect! The results in the table are live results from PHP 5.6.
For what it's worth, here is a breakdown of the wonky behavior of strtotime when determining a consistent frame of reference:
http://gamereplays.org/reference/strtotime.php
Basically only these strings will reliably give you the same date, no matter what day of the week you're currently on when you call them:
strtotime("next monday");
strtotime("this sunday");
strtotime("last sunday");
Assuming Monday as the first day of the week, this works:
echo date("M-d-y", strtotime('last monday', strtotime('next week', time())));
The following code should work with any custom date, just uses the desired date format.
$custom_date = strtotime( date('d-m-Y', strtotime('31-07-2012')) );
$week_start = date('d-m-Y', strtotime('this week last monday', $custom_date));
$week_end = date('d-m-Y', strtotime('this week next sunday', $custom_date));
echo '<br>Start: '. $week_start;
echo '<br>End: '. $week_end;
I tested the code with PHP 5.2.17 Results:
Start: 30-07-2012
End: 05-08-2012
How about this?
$first_day_of_week = date('m-d-Y', strtotime('Last Monday', time()));
$last_day_of_week = date('m-d-Y', strtotime('Next Sunday', time()));
This is what I am using to get the first and last day of the week from any date.
In this case, monday is the first day of the week...
$date = date('Y-m-d') // you can put any date you want
$nbDay = date('N', strtotime($date));
$monday = new DateTime($date);
$sunday = new DateTime($date);
$monday->modify('-'.($nbDay-1).' days');
$sunday->modify('+'.(7-$nbDay).' days');
Here I am considering Sunday as first & Saturday as last day of the week.
$m = strtotime('06-08-2012');
$today = date('l', $m);
$custom_date = strtotime( date('d-m-Y', $m) );
if ($today == 'Sunday') {
$week_start = date("d-m-Y", $m);
} else {
$week_start = date('d-m-Y', strtotime('this week last sunday', $custom_date));
}
if ($today == 'Saturday') {
$week_end = date("d-m-Y", $m);
} else {
$week_end = date('d-m-Y', strtotime('this week next saturday', $custom_date));
}
echo '<br>Start: '. $week_start;
echo '<br>End: '. $week_end;
Output :
Start: 05-08-2012
End: 11-08-2012
How about this?
$day_of_week = date('N', strtotime($string_date));
$week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
$week_last_day = date('Y-m-d', strtotime($string_date . " + " . (7 - $day_of_week) . " days"));
Just use date($format, strtotime($date,' LAST SUNDAY + 1 DAY'));
Try this:
function week_start_date($wk_num, $yr, $first = 1, $format = 'F d, Y')
{
$wk_ts = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101'));
$mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts);
return date($format, $mon_ts);
}
$sStartDate = week_start_date($week_number, $year);
$sEndDate = date('F d, Y', strtotime('+6 days', strtotime($sStartDate)));
(from this forum thread)
This is the shortest and most readable solution I found:
<?php
$weekstart = strtotime('monday this week');
$weekstop = strtotime('sunday this week 23:59:59');
//echo date('d.m.Y H:i:s', $weekstart) .' - '. date('d.m.Y H:i:s', $weekstop);
?>
strtotime is faster than new DateTime()->getTimestamp().
$monday = date('d-m-Y',strtotime('last monday',strtotime('next monday',strtotime($date))));
You have to get next monday first then get the 'last monday' of next monday. So if the given date is monday it will return the same date not last week monday.
$string_date = '2019-07-31';
echo $day_of_week = date('N', strtotime($string_date));
echo $week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
echo $week_last_day = date('Y-m-d', strtotime($string_date . " + " . (7 - $day_of_week) . " days"));
Given PHP version pre 5.3 following function gives you a first day of the week of given date (in this case - Sunday, 2013-02-03):
<?php
function startOfWeek($aDate){
$d=strtotime($aDate);
return strtotime(date('Y-m-d',$d).' - '.date("w",$d).' days');
}
echo(date('Y-m-d',startOfWeek("2013-02-07")).'
');
?>
$today_day = date('D'); //Or add your own date
$start_of_week = date('Ymd');
$end_of_week = date('Ymd');
if($today_day != "Mon")
$start_of_week = date('Ymd', strtotime("last monday"));
if($today_day != "Sun")
$end_of_week = date('Ymd', strtotime("next sunday"));
If you want Monday as the start of your week, do this:
$date = '2015-10-12';
$day = date('N', strtotime($date));
$week_start = date('Y-m-d', strtotime('-'.($day-1).' days', strtotime($date)));
$week_end = date('Y-m-d', strtotime('+'.(7-$day).' days', strtotime($date)));
A smart way of doing this is to let PHP handle timezone differences and Daylight Savings Time (DST). Let me show you how to do this.
This function will generate all days from Monday until Friday, inclusive (handy for generating work week days):
class DateTimeUtilities {
public static function getPeriodFromMondayUntilFriday($offset = 'now') {
$now = new \DateTimeImmutable($offset, new \DateTimeZone('UTC'));
$today = $now->setTime(0, 0, 1);
$daysFromMonday = $today->format('N') - 1;
$monday = $today->sub(new \DateInterval(sprintf('P%dD', $daysFromMonday)));
$saturday = $monday->add(new \DateInterval('P5D'));
return new \DatePeriod($monday, new \DateInterval('P1D'), $saturday);
}
}
foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday() as $day) {
print $day->format('c');
print PHP_EOL;
}
This will return datetimes Monday-Friday for current week. To do the same for an arbitrary date, pass a date as a parameter to DateTimeUtilities ::getPeriodFromMondayUntilFriday, thus:
foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00') as $day) {
print $day->format('c');
print PHP_EOL;
}
//prints
//2017-01-02T00:00:01+00:00
//2017-01-03T00:00:01+00:00
//2017-01-04T00:00:01+00:00
//2017-01-05T00:00:01+00:00
//2017-01-06T00:00:01+00:00
Only interested in Monday, as the OP asked?
$monday = DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00')->getStartDate()->format('c');
print $monday;
// prints
//2017-01-02T00:00:01+00:00
You parse the date using strptime() and use date() on the result:
date('N', strptime('%m-%d-%g', $dateString));
<?php
/* PHP 5.3.0 */
date_default_timezone_set('America/Denver'); //Set apprpriate timezone
$start_date = strtotime('2009-12-15'); //Set start date
//Today's date if $start_date is a Sunday, otherwise date of previous Sunday
$today_or_previous_sunday = mktime(0, 0, 0, date('m', $start_date), date('d', $start_date), date('Y', $start_date)) - ((date("w", $start_date) ==0) ? 0 : (86400 * date("w", $start_date)));
//prints 12-13-2009 (month-day-year)
echo date('m-d-Y', $today_or_previous_sunday);
?>
(Note: MM, dd and yyyy in the Question are not standard php date format syntax - I can't be sure what is meant, so I set the $start_date with ISO year-month-day)
I've come against this question a few times and always surprised the date functions don't make this easier or clearer. Here's my solution for PHP5 that uses the DateTime class:
/**
* #param DateTime $date A given date
* #param int $firstDay 0-6, Sun-Sat respectively
* #return DateTime
*/
function getFirstDayOfWeek(DateTime $date, $firstDay = 0) {
$offset = 7 - $firstDay;
$ret = clone $date;
$ret->modify(-(($date->format('w') + $offset) % 7) . 'days');
return $ret;
}
Necessary to clone to avoid altering the original date.
Another way to do it....
$year = '2014';
$month = '02';
$day = '26';
$date = DateTime::createFromFormat('Y-m-d H:i:s', $year . '-' . $month . '-' . $day . '00:00:00');
$day = date('w', $date->getTimestamp());
// 0=Sunday 6=Saturday
if($day!=0){
$newdate = $date->getTimestamp() - $day * 86400; //86400 seconds in a day
// Look for DST change
if($old = date('I', $date->getTimestamp()) != $new = date('I', $newdate)){
if($old == 0){
$newdate -= 3600; //3600 seconds in an hour
} else {
$newdate += 3600;
}
}
$date->setTimestamp($newdate);
}
echo $date->format('D Y-m-d H:i:s');
The easiest way to get first day(Monday) of current week is:
strtotime("next Monday") - 604800;
where 604800 - is count of seconds in 1 week(60*60*24*7).
This code get next Monday and decrease it for 1 week. This code will work well in any day of week. Even if today is Monday.
I found this quite frustrating given that my timezone is Australian and that strtotime() hates UK dates.
If the current day is a Sunday, then strtotime("monday this week") will return the day after.
To overcome this:
Caution: This is only valid for Australian/UK dates
$startOfWeek = (date('l') == 'Monday') ? date('d/m/Y 00:00') : date('d/m/Y', strtotime("last monday 00:00"));
$endOfWeek = (date('l') == 'Sunday') ? date('d/m/Y 23:59:59') : date('d/m/Y', strtotime("sunday 23:59:59"));
Here's a one liner for the first day of last week, and the last day of last week as a DateTime object.
$firstDay = (new \DateTime())->modify(sprintf('-%d day', date('w') + 7))
->setTime(0, 0, 0);
$lastDay = (new \DateTime())->modify(sprintf('-%d day', date('w') + 1))
->setTime(23, 59, 59);
Just to note that timestamp math can also be a solution. If you have in mind that 01.jan 1970 was a Thursday, then start of a week for any given date can be calculated with:
function weekStart($dts)
{ $res = $dts - ($dts+date('Z',$dts)+259200)%604800;
return $res + 3600*(date('I',$dts)-date('I',$res));
}
It is predictable for any timestamp and php version, using date-func ('Z', 'I') only for timezone and daylight-saving offsets. And it produces same results as:
strtotime(date('Y-m-d', $dts).' - '.(date('N', $dts)-1.' days');
and with (the best and the most elegant) mentioned:
strtotime('monday this week', $dts);

Categories