php - 根据频率计算一系列 future 日期的算法

标签 php algorithm date scheduler

我正在开发一个付款调度程序,它计划 n基于任意开始日期和一组频率(每日、每周、每月等)之一的付款,并且正在寻求一种通用算法来执行此操作。

我尝试了一种蛮力方法来做到这一点,通过限制频率并根据需要添加一定数量的天数、周数、月数。这适用于大多数目的。

当任意开始日期在每月 28 号之后并且频率介于每月和每年之间时,特别是对于“每月第一”和“每月最后”等频率,它会失败。因为第 29、30 和 31 天不会出现在所有月份中,所以添加像 date('2013-10-31')->addMonth(1) 这样的月份。具有不可预测的结果。添加像 date('2014-01-31')->addDays(30) 这样的月份也是如此再次,由于二月过短。

这个问题是否有一个通用的解决方案,而不需要我在任何给定月份移动任何给定频率所需的极其复杂的情况?

PHP 的奖励积分,但如果需要我可以翻译。

最佳答案

“加一个月”等等,由于月份长度不同而产生的烦恼确实令人恼火。

如果您的 PHP >= 5.2,解决方案是 DateTime class .

虽然使用此类获得完全控制很简单,但它并不是完全微不足道。

这是添加一个月的正确代码的一个版本。

// Variables defining the start date
// Example only - this could be any valid date
$year = '2013';
$month = '01';
$day = '31';

// set to the desired starting date and time
$the_date = new DateTime($year . '-' . $month . '-' . $day);

// Jump to the first day of this month
$the_date->modify("first day of this month");

// add 14 days, so we'll land on the 15th
$the_date->add(new DateInterval("P14D"));

// add 1 month - guaranteed to work!
$the_date->add(new DateInterval("P1M"));

// calculate how many days to add to 15 to get back to the **day** we started with...
// (as an integer, regardless of whether it is a valid day of the current month)
$number_days_to_add_back = intval($day) - 15;

// determine the last day of the month stored in $the_date
$test_last_date = clone $the_date;
$test_last_date->modify("last day of this month");
$day_last = $test_last_date->format('j'); // This provides the day, 01-31

// Test if adding $number_days_to_add_back runs past
// the end of the month; if so, adjust it so it won't run past
// the last day of the month
if (15 + $number_days_to_add_back > intval($day_last)) {
    $number_days_to_add_back = intval($day_last) - 15;
}

// Now make the final adjustment
$the_date->modify("" . $number_days_to_add_back . " day");

// Test it - a month has been added
$test = date_format($the_date, 'Y-m-d');

关于php - 根据频率计算一系列 future 日期的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19719734/

相关文章:

javascript - 以正确的顺序文件依赖

java - Android,日期不保存在数据库中

javascript - E.split 在 jquery 中附加日期作为数据时不是函数错误

r - 在 Shiny 中按日期过滤

php - 如何使用使用 `sqliteCreateFunction` 自定义的 LIKE 语句来转义参数化查询中的通配符?

algorithm - xsl 中的自定义分组

c++ - 在 int 中测试 4 个字节的零

php - 如何在 yii2 ActiveRecord 中使用查询缓存

php - 我想使用 PHP 更新 MySQL 数据库表

javascript - 包含 app.js Laravel 后 Bootstrap javascript 无法工作