PHP日期减去X天

时间:2014-12-16 09:56:49

标签: php mysql

我在PHP中有这个代码:

date('Y-m-d', strtotime("-7 days"))
我在SQL查询中使用的

$sql="SELECT * from billing_invoices WHERE due_date <= '".date('Y-m-d', strtotime("-7 days"))."' AND (status = 'Unpaid' or status = 'Part Paid') AND statement = '0000-00-00 00:00:00' group by customer_sequence ";

因此,如果日期为2014-12-16,则会显示2014-12-09

我希望能够运行此查询:

$sql="SELECT * from billing_invoices WHERE due_date <= '".date($_POST["date"], strtotime("-7 days"))."' AND (status = 'Unpaid' or status = 'Part Paid') AND statement = '0000-00-00 00:00:00' group by customer_sequence ";

但是返回的日期是当前日期,而不是距POSTED日期

的-7天

4 个答案:

答案 0 :(得分:5)

根据strtotime的PHP手册,有第二个参数,您可以在其中指定一个时间戳,然后使用时间戳代替当前时间

int strtotime ( string $time [, int $now ] )

所以你的代码应该是这样的:

date("Y-m-d", strtotime("-7 days", $_POST["date"]))

也许您必须先将日期转换为时间戳。根据{{​​1}}中的日期格式,这可能有效:

$_POST["date"]

答案 1 :(得分:0)

使用

  

有限区间

$sql="SELECT * from billing_invoices WHERE DATE_SUB(due_date , INTERVAL -7 DAY)' AND (status = 'Unpaid' or status = 'Part Paid') AND statement = '0000-00-00 00:00:00' group by customer_sequence ";

OR

$sql="SELECT * from billing_invoices WHERE DATE_SUB(now(), INTERVAL -7 DAY)' AND (status = 'Unpaid' or status = 'Part Paid') AND statement = '0000-00-00 00:00:00' group by customer_sequence ";

答案 2 :(得分:0)

SQL不知道什么是date($_POST["date"], strtotime("-7 days")) ....所以你可以使用它......

$sql="SELECT * from billing_invoices WHERE due_date <= '".DATE_SUB(CURDATE(),INTERVAL 30 DAY)."' AND (status = 'Unpaid' or status = 'Part Paid') AND statement = '0000-00-00 00:00:00' group by customer_sequence ";

答案 3 :(得分:0)

您可以使用MySQL中的DATE_SUB / INTERVAL函数执行此检查。

* NB。 - 确保将所输入的值转义为SQL。

 $sql="SELECT * 
   FROM billing_invoices 
   WHERE due_date <= DATE(DATE_SUB(".$_POST['date'].", INTERVAL -7 DAY))
   AND (status = 'Unpaid' OR status = 'Part Paid') 
   AND statement = '0000-00-00 00:00:00' 
   GROUP BY customer_sequence;";

您可以在此处找到有关使用DATE_SUB / INTERVAL的更多信息:http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-sub