gpt4 book ai didi

php - 在 PHP 中四舍五入到最近的可用时间段

转载 作者:可可西里 更新时间:2023-11-01 13:15:11 24 4
gpt4 key购买 nike

我已经为此苦苦挣扎了一个小时左右,却一无所获。基本上我需要将当前时间加上 30 分钟,然后四舍五入到下一个 15 分钟。

例子:

  • 如果现在是 20:00,则结果 = 20:45
  • 如果现在是 20:10,结果 = 20:45
  • 如果现在是 20:16,结果 = 21:00
  • 如果现在是 20:35,结果 = 21:15

我的 PHP 生锈了,我一直在混淆日期添加和舍入方法,试图让它工作,我知道这很简单 - 只是没有想法!

谢谢

最佳答案

我也会添加一个解决方案:

<?php

date_default_timezone_set('America/Los_Angeles');

$times = array();
$times[] = strtotime('00:07');
$times[] = strtotime('04:21');
$times[] = strtotime('20:00');
$times[] = strtotime('20:10');
$times[] = strtotime('20:16');
$times[] = strtotime('20:35');
$times[] = strtotime('23:15');


foreach($times as $time) {
echo date('m-d-Y H:i', $time) . ' becomes ' . date('m-d-Y H:i:s', roundToNearestInterval($time)) . "<br />\n";
}


function roundToNearestInterval($timestamp)
{
$timestamp += 60 * 30;
list($m, $d, $y, $h, $i, $s) = explode(' ', date('m d Y H i s', $timestamp));
if ($s != 0) $s = 0;

if ($i < 15) {
$i = 15;
} else if ($i < 30) {
$i = 30;
} else if ($i < 45) {
$i = 45;
} else if ($i < 60) {
$i = 0;
$h++;
}

return mktime($h, $i, $s, $m, $d, $y);
}

产量:

03-01-2012 00:07 becomes 03-01-2012 00:45:00
03-01-2012 04:21 becomes 03-01-2012 05:00:00
03-01-2012 20:00 becomes 03-01-2012 20:45:00
03-01-2012 20:10 becomes 03-01-2012 20:45:00
03-01-2012 20:16 becomes 03-01-2012 21:00:00
03-01-2012 20:35 becomes 03-01-2012 21:15:00
03-01-2012 23:15 becomes 03-02-2012 00:00:00

关于php - 在 PHP 中四舍五入到最近的可用时间段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9523738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com