首页 > 解决方案 > 如何在 PHP 中将日期和时间转换为特定范围

问题描述

例如,我有以下 php 日期:

2018-07-16 02:07:30
2018-07-16 02:17:30
2018-07-16 02:37:30
2018-07-16 02:47:30

我必须在语法上将以上日期转换为以下日期:

2018-07-16 02:15:00
2018-07-16 02:30:00
2018-07-16 02:45:00
2018-07-16 03:00:00

例如,如果分钟是 1-15 应该是 15,如果分钟是 16-30 应该是 30,如果分钟是 31-45 应该是 45,如果分钟是 46-60 应该是 00。

标签: php

解决方案


首先,您应该获取timestring起始日期,然后设置分数 900(秒),它等于 15 分钟。您可以将 900 秒转换为分钟,然后获取时间并计算分钟,并timestring_fraction通过$timestring_fraction = $timestring % $fraction;此操作创建新日期date('Y-m-d H:i:s', $minutes)

代码

$date = '2018-07-16 02:37:30';
$timestring = strtotime($date);

// 900 seconds which is equal to 15 minutes
$fraction = 900;
$timestring_fraction = $timestring % $fraction;

$minutes = $timestring + ($fraction - $timestring_fraction);
$updated_date = date('Y-m-d H:i:s', $minutes);

echo $updated_date;

输出

// 2018-07-16 02:07:30
2018-07-16 02:15:00

// 2018-07-16 02:17:30
2018-07-16 02:30:00

// 2018-07-16 02:37:30
2018-07-16 02:45:00

// 2018-07-16 02:47:30
2018-07-16 03:00:00

更新的答案

如果时间是这样的,2018-07-16 02:30:00那么解决方案将是

$timestring_fraction = $timestring % $fraction;

if ($timestring_fraction === 0) {
    echo $date;
}
else {
    $minutes = $timestring + ($fraction - $timestring_fraction);
    $updated_date = date('Y-m-d H:i:s', $minutes);

    echo $updated_date;
}

因为在这种情况下,如果分钟完全相同,即 15、30、45 或 00,那么时间分数也将为零,因此您需要在创建新日期之前检查时间分数


推荐阅读