PHP日期:在闰年内计算日期的问题

时间:2016-03-03 09:30:24

标签: php datetime

我正在计算每周的价值,比较上一周和前一年的同一天。由于我们只是闰年,我的方法会产生问题。

我正在计算这样的日期并执行相应的选择:

$today_raw = date('Y-m-d');
$yearAgo = date('Y-m-d', strtotime('-1 year', strtotime($today_raw)));
$weekAgo = date('Y-m-d', strtotime('-6 day', strtotime($today_raw)));
$weekYearAgo = date('Y-m-d', strtotime('-1 year', strtotime($weekAgo)));

$stmt_currentWeek = $pdo->prepare("SELECT X FROM Y WHERE Z BETWEEN '$weekAgo' AND '$today'");
$stmt_weekLastYear = $pdo->prepare("SELECT X FROM Y WHERE Z BETWEEN '$weekYearAgo' AND '$yearAgo'");

SELECT显然会返回错误的值,因为$weekYearAgo完全错误,因为它不反映闰年差异。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

只需使用mysql DATE功能:

$stmt_currentWeek = $pdo->prepare("SELECT X FROM Y WHERE Z >= DATE_SUB(NOW(), INTERVAL 1 WEEK)");
$stmt_weekLastYear = $pdo->prepare("SELECT X FROM Y WHERE Z BETWEEN DATE_SUB(DATE_SUB(NOW(), INTERVAL 1 YEAR), INTERVAL 1 WEEK) AND DATE_SUB(NOW(), INTERVAL 1 YEAR)");

1年1周AGO:

DATE_SUB(DATE_SUB(NOW(), INTERVAL 1 YEAR), INTERVAL 1 WEEK)

1年AGO:

DATE_SUB(NOW(), INTERVAL 1 YEAR)

AGO 1周:

DATE_SUB(NOW(), INTERVAL 1 WEEK)

在第一个SQL中你不需要1 WEEK AGO和现在你可以将它重写为> = 1 WEEK AGO