php - 如何在 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。
解决方案
首先,您应该获取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,那么时间分数也将为零,因此您需要在创建新日期之前检查时间分数
推荐阅读
- logstash - Logstash TLS 握手失败
- swift - 结合 SwiftUI 在 Swift5 中存储数据的最常见方式
- autodesk-forge - 如何实现“Autodesk.AEC.LevelsExtension”和“Autodesk.AEC.Minimap3DExtension”
- javascript - 如何在d3中创建一条线?
- python - 在 HED 算法中检测大颗粒旁边的小颗粒的替代方法
- visual-studio-code - 无法在 RHEL8 上以 root 身份运行 Visual Studio 代码
- asp.net - 在 Google Colab 上安装 .NET Core
- react-native - 无法在 React Native 0.61.5 新项目上安装 pod
- haskell - 使用最近的集合重复从 Postgres 获取值
- javascript - findByIdAndUpdate 不更新