thomas.io

November 13, 2017

How to store hours in a database

The easiest way I found to store hours (24-time format) in a database is to convert them in integers.

So here are the functions I used to do the conversion:

<?php
    
    function intToHour($int)
    {
        $minutes = $int % 60;
        $hours = $int / 60;

        return sprintf("%02d", floor($hours)) . ":" . sprintf("%02d", $minutes);
    }

    function hourToInt($hour)
    {
        $array = explode(':', $hour);

        return ($array[0] * 60) + $array[1];
    }
    

So now you can do:

echo hourToInt("13:37"); // 817

And the opposite:

echo intToHour("817"); // 13:37

And if you use Laravel, Accessors & Mutators make it painless, just place this in your model:

    public function getHourAttribute($value)
    {
        return intToHour($value);
    }

    public function setHourAtAttribute($value)
    {
        $this->attributes['hour'] = hourToInt($value);
    }

That way you don't have to worry about anything!