如何找到一周中两天之间的天数?

How to finding the number of days between two days of the week?

如何使用 PHP 查找两天 而不是日期 之间的天数?

我知道如何获取两个日期之间的天数,但我的输入值是日期名称(不知道日期)。

Inputs/Outputs:

WednesdaySaturday returns 3

SundayWednesday returns 3

使用 PHP date_diff() 函数 (docs)。

$datetime1 = date_create($date_1);
$datetime2 = date_create($date_2);

$interval = date_diff($datetime1, $datetime2);

echo $interval->format('%d'); // For days

根据说明,您可以创建任意星期六和星期三来计算它:

$datetime1 = date_create(date('Y-m-d',strtotime('wednesday')));
$datetime2 = date_create(date('Y-m-d',strtotime('saturday')));

$interval = date_diff($datetime1, $datetime2);

echo $interval->format('%d'); // For days

会 return “3”,但取决于你什么时候 运行 它。

你可以在新的DateTime中写上解析日期的名称class:

<?php
  $datetime1 = new DateTime('Sunday');
  $datetime2 = new DateTime('Wednesday');
  $interval = $datetime1->diff($datetime2);
  echo $interval->format('%R%a days');
  ?>

下面还有一行版本:

echo (new DateTime('Sunday'))->diff(new DateTime('Wednesday'))->format('%a days');

您的任务似乎根本不需要日期函数。一个简单的查找数组就足够了。

  1. 从结束日的整数中减去开始日的整数值。
  2. 如果差异为零或更小,则总是 return 正确的正数天数加 7。

代码:(Demo)

function daysUntil($start, $end) {
    $lookup = [
        'Sunday' => 0,
        'Monday' => 1,
        'Tuesday' => 2,
        'Wednesday' => 3,
        'Thursday' => 4,
        'Friday' => 5,
        'Saturday' => 6
    ];
    $days = $lookup[$end] - $lookup[$start] + ($lookup[$end] <= $lookup[$start] ? 7 : 0);
    return "{$days} days from {$start} to {$end}\n";
}

echo daysUntil('Wednesday', 'Saturday');  // Thursday, Friday, Saturday
echo daysUntil('Monday', 'Friday');       // Tuesday, Wednesday, Thursday, Friday
echo daysUntil('Thursday', 'Thursday');   // [assumed next week]
echo daysUntil('Friday', 'Monday');       // Saturday, Sunday, Monday
echo daysUntil('Saturday', 'Sunday');     // Sunday
echo daysUntil('Sunday', 'Saturday');     // Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
echo daysUntil('Sunday', 'Wednesday');    // Monday, Tuesday, Wednesday

输出:

3 days from Wednesday to Saturday
4 days from Monday to Friday
7 days from Thursday to Thursday
3 days from Friday to Monday
1 days from Saturday to Sunday
6 days from Sunday to Saturday
3 days from Sunday to Wednesday

或者您可以用 4 个函数调用替换查找数组并获得相同的结果:(Demo)

function daysUntil($start, $end) {
    $days = date('w', strtotime($end)) - date('w', strtotime($start));
    $days += $days < 1 ? 7 : 0;
    return "{$days} days from {$start} to {$end}\n";
}