简体   繁体   English

PHP获取昨天的日期,除非周末

[英]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') . 您可以使用date('w')检查当前星期几。 Note that Sunday is 0, and Saturday is 6. 请注意,星期日为0,星期六为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. 基本上,如果是周末,则要求最后一个星期五,否则,则要求PHP昨天。

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 . 在我们今天的情况下,即Tuesday, June 14th 2016Tuesday, June 14th 2016它将返回2016-06-13

For more information about the date function: http://php.net/manual/en/function.date.php 有关日期函数的更多信息: http : //php.net/manual/en/function.date.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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