You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为PHP时间短代码集成向上取整至最近15分钟功能

整合向上取整到最近15分钟的修改方案

修改后的完整代码

function timeZone_funch( $atts ) 
{
    extract(shortcode_atts(array('timezone' => 'Europe/Berlin'), $atts)); 
    /* Europe/Berlin is default Timezone */
    $output = '';
    if (in_array($timezone, DateTimeZone::listIdentifiers()))
    {
        // 使用DateTime类处理时区与时间,避免全局时区冲突问题
        $dt = new DateTime('now +30 minutes', new DateTimeZone($timezone));
        // 实现向上取整至最近15分钟
        $minutes = (int)$dt->format('i');
        $remainder = $minutes % 15;
        if ($remainder !== 0) {
            $dt->modify('+' . (15 - $remainder) . ' minutes');
        }
        // 格式化为H:i格式输出
        $output = $dt->format('H:i');
    }
    else {
        $output = "Invalid Timezone";
    }

    return $output;
}
add_shortcode( 'current_time', 'timeZone_funch' );

关键修改说明

  • 替换时间处理逻辑:放弃原有的date_default_timezone_set+strtotime组合,改用DateTime类直接绑定指定时区,避免全局时区设置可能引发的其他问题,同时时间计算更精准。
  • 添加向上取整逻辑:
    1. 提取当前时间加30分钟后的分钟数
    2. 计算分钟数对15取余的结果,若余数不为0,就给当前时间加上15-余数分钟,直接跳转到下一个15分钟节点
  • 保留原有核心功能:时区有效性验证、默认时区设置、无效时区提示的逻辑完全保留,确保原有短代码的兼容性。

内容的提问来源于stack exchange,提问作者Chris Grundmann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:55:17