如果我想在PHP中生成多个到期日期,请问能给我推荐最好的解决方案吗?
我有这样的事情:
Name | activation_date | months
--------------------------------------
Record1 04/05/2016 3
Record2 01/01/2016 6
Record3 12/12/2015 12
对于
record1
,我使用以下function
,$expriration_date = date('Y-m-d', strtotime("+{$row['months']} months", strtotime($expriration_date)));
要从
expiration date
开始生成"activation_date"
,然后将其保存到我的SQL
Database
中。问题是我想生成多个周期性的
expiration dates
。例如,对于
record1
,到期日期应为:04/08/2016
,04/11/2016
,04/02/2016
,等等,为5年,我希望对所有记录都这样做。在五年内,
Record1
应该具有20个到期日期,Record2
应该具有10个到期日期,依此类推。编辑
间隔时间可以是3、6、12、24、36、48和50个月,我想生成5年的定期到期日期。
如何在PHP中做到这一点?
而且,有没有办法通知用户最近的到期日期呢?
我读过有关cron-job的文章:这是唯一的解决方案?
感谢你的支持。
最佳答案
您可以使用简单的for loop
for ($m = $months; $m <=60 ; $m += $months){
//add $m to activation_date
$expriration_date = DateTime::createFromFormat('Y-m-d', $activation_date);
$expriration_date->add(new DateInterval('P'.$m.'M'));
//do something with $expriration_date
}
您可以通过查询来做到这一点(但不要发布使用的数据库引擎)。
该查询适用于大多数流行的数据库引擎:
WITH
intervals AS
( SELECT 1 AS n, 3 AS m
UNION ALL SELECT 2 AS n, 3 AS m
UNION ALL SELECT 3 AS n, 3 AS m
UNION ALL SELECT 4 AS n, 3 AS m
UNION ALL SELECT 5 AS n, 3 AS m
UNION ALL SELECT 6 AS n, 3 AS m
UNION ALL SELECT 7 AS n, 3 AS m
UNION ALL SELECT 8 AS n, 3 AS m
UNION ALL SELECT 9 AS n, 3 AS m
UNION ALL SELECT 10 AS n, 3 AS m
UNION ALL SELECT 11 AS n, 3 AS m
UNION ALL SELECT 12 AS n, 3 AS m
UNION ALL SELECT 13 AS n, 3 AS m
UNION ALL SELECT 14 AS n, 3 AS m
UNION ALL SELECT 15 AS n, 3 AS m
UNION ALL SELECT 16 AS n, 3 AS m
UNION ALL SELECT 17 AS n, 3 AS m
UNION ALL SELECT 18 AS n, 3 AS m
UNION ALL SELECT 19 AS n, 3 AS m
UNION ALL SELECT 20 AS n, 3 AS m
UNION ALL SELECT 1 AS n, 6 AS m
UNION ALL SELECT 2 AS n, 6 AS m
UNION ALL SELECT 3 AS n, 6 AS m
UNION ALL SELECT 4 AS n, 6 AS m
UNION ALL SELECT 5 AS n, 6 AS m
UNION ALL SELECT 6 AS n, 6 AS m
UNION ALL SELECT 7 AS n, 6 AS m
UNION ALL SELECT 8 AS n, 6 AS m
UNION ALL SELECT 9 AS n, 6 AS m
UNION ALL SELECT 10 AS n, 6 AS m
UNION ALL SELECT 1 AS n, 12 AS m
UNION ALL SELECT 2 AS n, 12 AS m
UNION ALL SELECT 3 AS n, 12 AS m
UNION ALL SELECT 4 AS n, 12 AS m
UNION ALL SELECT 5 AS n, 12 AS m)
SELECT name, your_db_func_to_add_month(activation_date, n * m) AS expiration_dates
FROM something
INNER JOIN intervals ON months = m
WHERE activation_date BETWEEN your_db_func_to_add_month(:testdate, -60) AND :testdate
:testdate是绑定到查询的参数,
your_db_func_to_add_month例如在mysql中:
DATE_ADD(:testdate, INTERVAL 60 MONTH)
编辑:
如果使用以上数据定义表间隔,则只需选择。对于MySQL,此查询如下所示:
SELECT name, DATE_ADD(activation_date, INTERVAL n * m MONTH) (activation_date, n * m) AS expiration_dates
FROM something
INNER JOIN intervals ON months = m
WHERE activation_date BETWEEN DATE_ADD(:testdate, - INTERVAL 60 MONTH) AND :testdate
关于php - 如何在PHP中计算多个到期日期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36446325/