如何在PHP中计算多个到期日期

时间:2016-04-06 09:03:19

标签: php mysql sql date cron

如果我想在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/201604/11/201604/02/2016等等,为期5年,我想对所有记录做同样的事情。 在五年内,Record1应该有20个到期日期,Record2应该有10个到期日期等等。

编辑

间隔时间可以是3,6,12,24,36,48和50个月,我想定期生效5年。

我如何在PHP中执行此操作? 此外,有没有办法向用户通知最近的到期日期,然后?
我读过有关cron-job的信息:这是唯一的解决方案吗?

感谢您的支持!

1 个答案:

答案 0 :(得分:1)

您可以使用简单的for loop

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

您可以通过查询来执行此操作(但您不会发布您使用的数据库引擎) 此查询适用于大多数流行的数据库引擎:

DATE_ADD(:testdate, INTERVAL 60 MONTH)

:testdate是绑定到查询的参数,
your_db_func_to_add_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

修改
如果使用上面的数据定义表格间隔,则只需选择。对于MySQL,此查询如下所示:

SELECT * FROM student 
LEFT JOIN class ON s_class_id=c_id
WHERE parent_id='$update_id'