0
1

More than 5 years have passed since last update.

【PHP】日時を、指定した分単位に切り上げ

Last updated at Posted at 2017-10-02

概要

日時を、指定した間隔で切り上げたいシーンがあったので、実装。 完全に、備忘録レベルですが意外と使いそうなので、残しておきます。

実装

/**
 * 指定した分で切り上げたタイムスタンプを返す
 * 
 * @param int $timestamp タイムスタンプ
 * @param int $margin_minutes 切り上げる単位(分)
 * @return int タイムスタンプ
 */
function ceilDatetime($timestamp, $margin_minutes = 20){
    $_year = date('Y', $timestamp);
    $_month = date('m', $timestamp);
    $_day = date('d', $timestamp);
    $_hour = date('H', $timestamp);
    $_minute = date('i', $timestamp);

    if($_minute % $margin_minutes) $_minute += $margin_minutes - ($_minute % $margin_minutes);

    return mktime($_hour, $_minute, 0, $_month, $_day, $_year);
}

実行例

サンプルコード

sample.php
<?php

$dates = array(
    '2017-10-01 00:11',
    '2017-10-01 00:20',
    '2017-10-01 00:35',
    '2017-10-01 00:55',
    '2017-10-01 23:55',
    );

foreach($dates as $v){
    echo date('Y-m-d H:i:s', ceilDatetime(strtotime($v))) . "\n";
}

結果

2017-10-01 00:20:00
2017-10-01 00:20:00
2017-10-01 00:40:00
2017-10-01 01:00:00
2017-10-02 00:00:00
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1