php - 使用 MySQL 进行时间计算

标签 php mysql date mysqli

我正在为一位钢琴调音师客户编写一个时间记录程序,并且我编写了以下 PHP 代码来为记录提供“待办事项”状态:

$last_tuned = '2017-01-05';
$tuning_period = 3;

$month_last_tuned = date('Y-m', strtotime(date('Y-m-d', strtotime($last_tuned))));

$next_tuning = date('Y-m', strtotime($month_last_tuned.(' +'.$tuning_period.' months')));

if (time() > strtotime($next_tuning.' -1 months')) {
    if (time() > strtotime($next_tuning)) {
        return 'late';
    } else {
        return 'upcoming';
    }
}

如您所见,$last_tuned 变量采用日期(YYYY-MM-DD) 格式。然后将其转换为 (YYYY-MM) 格式。

转换后,与 $tuning_period 相同的额外月份数将添加到 $month_last_tuned 变量中,为我们提供月份和年份值,以便我们需要时使用添加新记录。

如果当前时间(使用 time() 找到)大于 $next_tuning 变量 - 1 个月,则返回任务即将进行。如果它位于 $next_tuning 变量之后,则返回任务迟到

我现在必须编写一个 MySQL 查询来列出即将返回或迟到的项目。

我该如何在 MySQL 中编写这个?我不太擅长 MySQL 函数,如果能提供一些帮助,我将不胜感激。

我的逻辑尝试是:

SELECT * FROM records
 // The next lines are to get the most recent month_last_tuned value and add the tuning_period variable
 WHERE 
    NOW() > (SELECT tuning_date FROM tunings ORDER BY tuning_date ASC LIMIT 1)
       +
    (SELECT tuning_period FROM records WHERE records.id = INITIAL CUSTOMER ID)

我知道这是完全错误的。不过逻辑已经差不多了。

我的数据库架构如下:

Schema

我希望从查询返回的行与上面 PHP 代码中的“迟到”或“即将到来”值相同。这意味着返回的行将在下一次调整日期的 1 个月内(​​根据上次调整加上调整周期计算)。

谢谢!

最佳答案

您可能最好使用 DateTime 对象,而不是操作日期字符串。

$last_tuned = '2017-01-05';
$tuning_period = 3; // months

$dt_last_tuned = DateTimeImmutable::createFromFormat('Y-m-d',$last_tuned);
$dt_next_tuning = $dt_last_tuned->add(new DateInterval('P3M'));
$dt_now = new DateTimeImmutable();
$dt_tuning_upcoming = $dt_next_tuning->sub(new DateInterval('P1M'));

if( $dt_now > $dt_next_tuning) {
    return 'late';
}
if( $dt_now > $dt_tuning_upcoming) {
    return 'upcoming';
}

您还可以在 MySQL 查询中使用这些 DateTime 对象,方法是根据需要构建查询并传递类似 $dt_next_tuning->format('Y-m-d H:i:s'); 的内容。

但是,考虑到您的表结构,获取所有相关记录并处理它们可能会更容易。确切地说出这些部分是如何组合在一起的有点困难,但一般来说 MySQL 不应该用于“处理”东西。

关于php - 使用 MySQL 进行时间计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42613302/

相关文章:

php - 在php中自定义日期格式到mysql

php - 找不到两位数的月份 Laravel 中缺少数据

php - Zend Framework 中的 join SQL 错误

javascript - 使用 html 选择和日期的依赖日期选择器有意义

swift - 如何快速计算跨越两天的两次之间的正确时间间隔?

php - php总是需要连接吗?

php - 有什么技巧可以在 Wordpress 中使用 Yii 吗?

mysql - 如何从 wordpress docker 建立数据库连接

asp.net - 在 ASP.NET 应用程序中使用 mySql 数据

sql - 在同一列上迭代时计算持续时间