Clearer Time Values with Carbon

Table of Contents

Lots of applications involve date and time manipulation. Whether it's figuring out what day of the week it is, how many seconds are in a week or how many hours are in a century.

Quite often, you'll see something like:

$minutesInAWeek = 7 * 24 * 60

On a small scale, it's quite clear what is going on, but if you wrap this bit of logic in a function or another calculation, you can quickly lose sight of what 60 represents.

Luckily, Carbon provides a set of constants that can clear it up, making it easy to see what each number represents.

Lets take our example above and use these constants to make what's happening clearer:

use Carbon\Carbon;

$minutesInAWeek = Carbon::DAYS_PER_WEEK * Carbon::HOURS_PER_DAY * Carbon::MINUTES_PER_HOUR;

Yes, it's verbose. But this kind of verbosity is good, in my opinion.

If we wanted to take this further and figure out how many seconds are in a year, we could do:

use Carbon\Carbon;

$minutesInAWeek = Carbon::DAYS_PER_WEEK * Carbon::HOURS_PER_DAY * Carbon::MINUTES_PER_HOUR;

$secondsInAYear = $minutesInAWeek * Carbon::SECONDS_PER_MINUTE * Carbon::WEEKS_PER_YEAR;

There's some more constants too, you can check out the full list in the documentation.

Enjoyed this post or found it useful? Please consider sharing it on Twitter.