PHP get yesterdays date unless weekend - php

I need to get yesterday's date to show the market close date. This only applies to Monday through Friday as the markets are not open on the weekend. Using this format how would I do that?
<?php
$yesterday = date("Y-m-d", mktime(0, 0, 0, date("m") , date("d")-1,date("Y")));
echo $yesterday;
?>

Here's one way to do it:
$date= new \DateTime();
$oneDay = new \DateInterval('P1D');
$date->sub($oneDay);
if ('Sunday' === $date->format('l')) {
$date->sub($oneDay);
}
if ('Saturday' === $date->format('l')) {
$date->sub($oneDay);
}
echo $date->format('Y-m-d');
I just get today's date, subtract one day, and check to see if it is a Sunday. If so, subtract a day. Then I do the same thing for a Saturday. Ultimately you end up with the last weekday.
Keep in mind this is different then business day's as that Friday may be a holiday and the markets may be closed.

You could check what day the current week day is with date('w').
Note that Sunday is 0, and Saturday is 6.
And with that information, you can do:
$yesterday = strtotime(date('w') == 0 || date('w') == 6 ? 'last friday' : 'yesterday');
echo date('Y-m-d', $yesterday);
Basically, if it's a weekend, you ask for the last friday, otherwise, you ask PHP for yesterday.
If you don't like it in one line:
$w = date('w');
if($w == 0 || $w == 6)
$yesterday = strtotime('last friday');
else
$yesterday = strtotime('yesterday');
$yesterday = date('Y-m-d', $yesterday);
In our case today, Tuesday, June 14th 2016, it will return 2016-06-13.
For more information about the date function: http://php.net/manual/en/function.date.php

Related

How can I make date("W") start in Sunday and end on saturday? [duplicate]

I need to get week number in php where week should be calculated from sunday. By default its from monday. Please help me to find a way how to get week number considering sunday as starting day.
In php manual
ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)
But I need to get week number of year, weeks starting on sunday.
thanks
Try this:
$week = intval(date('W'));
if (date('w') == 0) { // 0 = Sunday
$week++;
}
echo $week;
Not sure if the logic is right though;
The first solution is not correct on Jan 01, 2017 or any year that begins on a Sunday.
Try this:
$date = date('Y-m-d');
echo strftime("%U", strtotime($date ) );
To expand on silkfire answer and allow for it wrapping around years
if($date->format('w') == 0){
if(date('W',strtotime($date->format('Y')."-12-31"))==52 and $date->format('W') == 52){
$week = 1;
}
elseif(date('W',strtotime($date->format('Y')."-12-31"))==53 and $date->format('W') == 53){
$week = 1;
}
else{
$week++;
}
}
Try this one. to get sunday day must -1 day.
$date = "2015-05-25";
echo date("W", strtotime("-1 day",strtotime($date)));
You should try with strftime
$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
I solved this like this:
function getWeekOfYear( DateTime $date ) {
$dayOfweek = intval( $date->format('w') );
if( $dayOfweek == 0 ) {
$date->add(new DateInterval('P1D'));
}
$weekOfYear = intval( $date->format('W') );
return $weekOfYear;
}
I know this topic is old, but this is a shorter way to do it with elvis operator and "+7 day" expression for strtotime():
$week=date("W",strtotime(date("w")==1?"+7 day":"+0 day"));
if $date("w") returns true means today is a day between tuesday and sunday (1-6), so, we can return today week ('today').
if returns false, it means is monday (0), so, we should return the next day ('+1 week').
This way we don't need to care about last or first day of year or check if current year has 52 or 53 weeks.
Edited: the previous answer (and others in this topic) doesn't work for this year because januray 1st is monday, so, it needs to be 1 week ago (-1 week) excluding sunday (day 6).
date("W",strtotime(date("w")?'-7 day':'+0 day'));
I think a condition asking if januray 1st is monday could work, but I didn't test it yet, I will come back with an answer later
For a custom day you could use this:
$date = strtotime('2018-04-30'); // (it is monday)
if(date("w",strtotime(date('Y',$date).'-01-01'))==1){ // if first day of year is monday
$week = strtotime(date('w',$date)?"-7 day":"+0 day",$date); // and today is sunday, sub a week
$week = date("W",$week);
}else{ // if is not monday
$week = strtotime(date('w',$date)==1?"+7 day":"+0 day",$date); // and today is monday, add a week
$week = date("W",$week);
}
Building on #silkfire's answer:
$year = date('Y');
$week_no = date('W');
if (date('w') == 0) { // 0 = Sunday
$week_no++;
}
// We shifted the week but the week still starts on a Monday.
$weekStartDate = new DateTime();
$weekStartDate->setISODate($year,$week_no);
// Shift start date to Sunday
$weekStartDate->add(DateInterval::createFromDateString('-1 day'));
Tested in php 5.6 Debian 7
function getWeekNumber(\DateTime $_date)
{
$week = intval($_date->format('W'));
if(intval($_date->format('w')) == 0) {
$week = intval($_date->format('W')) == ( 52 + intval($_date->format('L')) ) ? 1 : $week + 1;
}
return $week;
}
I needed to ADD day instead of subtracting to get Alghi Fari's answer to work.
$date = "2022-11-13";
echo date("W", strtotime("+1 day",strtotime($date)));

How to set the "first day of the week" to Thursday in PHP

I want to set the first day of the week to Thursday (not Sunday or Monday), because it's the company's cut-off date.
I already have a code to determine the current week number of a date but it starts in Sunday or Monday.
How to modify these to my preference?
function findweek($date) {
$monthstart=date("N",strtotime(date("n/l/Y",strtotime($date))));
$newdate=(date("j",strtotime($date))+$monthstart)/7;
$ddate=floor($newdate);
if($ddate != $date) {
$ddate++;
}
return $ddate;
}
http://php.net/manual/en/datetime.formats.relative.php says that as of PHP version 5.6.23, 7.0.8 "Weeks always start on monday. Formerly, sunday would also be considered to start a week." That said, is your problem that the number of weeks returned might be incorrect depending on whether today falls on or before Thursday of the current week? Maybe try something like this:
$date = new DateTime();
$week = intval($date->format('W'));
$day = intval($date->format('N'));
echo $day < 4 ? $week-1 : $week;
If subtracting 1 isn't the answer you could play around with addition/subtraction, comparing the result with the actual answer you know to be true until you get the right formula. Hope this helps!
This should work.
function findweek($date, $type = "l") {
$time = strtotime($date);
return date($type, mktime(0, 0, 0, date("m", $time) , date("d", $time)-date("d", $time)+1, date("Y", $time)));
}
echo findweek('2015-09-16');

Calculate day of month with month, year, day of week and number of week

How can I calculate the day of month in PHP with giving month, year, day of week and number of week.
Like, if I have September 2013 and day of week is Friday and number of week is 2, I should get 6. (9/6/2013 is Friday on the 2nd week.)
One way to achieve this is using relative formats for strtotime().
Unfortunately, it's not as straightforward as:
strtotime('Friday of second week of September 2013');
In order for the weeks to work as you mentioned, you need to call strtotime() again with a relative timestamp.
$first_of_month_timestamp = strtotime('first day of September 2013');
$second_week_friday = strtotime('+1 week, Friday', $first_of_month_timestamp);
echo date('Y-m-d', $second_week_friday); // 2013-09-13
Note: Since the first day of the month starts on week one, I've decremented the week accordingly.
I was going to suggest to just use strtotime() in this fashion:
$ts = strtotime('2nd friday of september 2013');
echo date('Y-m-d', $ts), PHP_EOL;
// outputs: 2013-09-13
It seems that this is not how you want the calendar to behave? But it is following a (proper) standard :)
This way its a little longer and obvious but it works.
/* INPUT */
$month = "September";
$year = "2013";
$dayWeek= "Friday";
$week = 2;
$start = strtotime("{$year}/{$month}/1"); //get first day of that month
$result = false;
while(true) { //loop all days of month to find expected day
if(date("w", $start) == $week && date("l", $start) == $dayWeek) {
$result = date("d", $start);
break;
}
$start += 60 * 60 * 24;
}
var_dump($result); // string(2) "06"

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"));

how to find date of last thursday of the month in php?

how to find date of last thursday of the month in php ?
it is for the payment thing. staffs needs to paid on last thursday of the month on which they have submitted invoices. I am having hard time finding out the date of last thursday of month
thanks
abhinab
PHP >= 5.3:
<?php
$date = strtotime('last thu of this month');
echo date('d.m.Y H:i:s', $date);
PHP < 5.3:
<?php
$date = strtotime(sprintf('+1 month %s %s', date('F'), date('Y')));
while (date('D', $date) !== 'Thu') {
$date -= 86400;
}
echo date('d.m.Y H:i:s', $date);
(didn't find a better way to do this)
Output:
30.06.2011 00:00:00
Find the first day of the month right after.
Walk backwards one day at a time until you hit a Thursday.

Categories