简体   繁体   中英

PHP get yesterdays date unless weekend

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM