【问题标题】:Monday 2 weeks from sunday last week. How?从上周的星期日开始的第 2 周星期一。如何?
【发布时间】:2021-09-16 18:07:32
【问题描述】:

我在试图弄清楚如何获取 2 周工资单的范围时遇到了一些挑战。

我将如何修改 -2W 案例?

$from = null;
$to = null;

switch ($range) {
  case '1D':
    // code...
    $from = date('Y-m-d ', strtotime('today')) . '00:00:00';
    $to = date('Y-m-d ', strtotime('today')) . '23:59:59';
    $objectView->historyFrom = date('D, F j');
    $objectView->historyTo = date('D, F j');
    break;
  case '1W':
    // code...
    $from = date('Y-m-d ', strtotime('monday this week')) . '00:00:00';
    $to = date('Y-m-d ', strtotime('sunday this week')) . '23:59:59';
    $objectView->historyFrom = date('D, F j', strtotime('monday this week'));
    $objectView->historyTo = date('D, F j', strtotime('sunday this week'));
    break;
  case '-1W':
    // code...
    $from = date('Y-m-d ', strtotime('monday last week')) . '00:00:00';
    $to = date('Y-m-d ', strtotime('sunday last week')) . '23:59:59';
    $objectView->historyFrom = date('D, F j', strtotime('monday last week'));
    $objectView->historyTo = date('D, F j', strtotime('sunday last week'));
    break; 
  case '-2W':
    // code...
    $from = date('Y-m-d ', strtotime('monday previous to last week')) . '00:00:00';
    $to = date('Y-m-d ', strtotime('sunday last week')) . '23:59:59';
    $objectView->historyFrom = date('D, F j', strtotime('monday last week'));
    $objectView->historyTo = date('D, F j', strtotime('sunday last week'));
    break; 
  default:
    // code...
    $from = date('Y-m-d ', strtotime('today')) . '00:00:00';
    $to = date('Y-m-d ', strtotime('today')) . '23:59:59';
    $objectView->historyFrom = date('D, F j');
    $objectView->historyTo = date('D, F j');
    break;
}

【问题讨论】:

  • 今天是August 30 还是September 6
  • 没错..!
  • 不!哪一个?他们之间有一个 OR。
  • 8 月 30 日是正确的。
  • 哇。如果您使用 PHP 处理日期的最佳工具(请参阅 DateTime),这可以减少到仅几行代码。

标签: php datetime


【解决方案1】:

你真的应该看看DateTime 可能是DatePeriod。但是要使用现有代码回答这个问题,我认为您需要两种格式,一种如果今天是星期一,另一种如果不是:

if(date('w') == '1') {
    $from = date('Y-m-d ', strtotime('-2 weeks');
    //or '-14 days'
} else {
    $from = date('Y-m-d ', strtotime('previous monday -2 weeks'));
    //or 'previous monday -14 days'
}

有人可能会找到一种对两者都适用的格式。

【讨论】:

  • 喜欢这个班轮吗? $datetime_from = (new DateTime($thestime))->sub(DateInterval::createFromDateString('45 minutes'))->format('Y-m-d H:i')
  • 类似的东西,但我没有太多或一段时间没有使用间隔。
猜你喜欢
  • 2012-11-27
  • 2018-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
相关资源
最近更新 更多