Back to blogs

Tech & Trends

21. 03. 2022

Creating a Neat DateTime Helper Function in PHP

by Ricardo Čerljenko

Let me start with a statement: I’m not a big fan of global helper functions being included in the project, but sometimes it’s a good thing to have that little helper functions here and there.

Working with DateTime in PHP could be a real pain if you don’t take advantage of popular libraries like Carbon. It’s all good until you have to convert dates provided on user input into another timezone (e.g. UTC) and vice versa. Other example could be that you have to manage various input DateTime formats, and sanitize them into a consistent one before saving it to the database.

I will show you how I handled that by creating a DateTime helper function which will take any DateTime format and convert it into a consistent one with the power of Carbon library.

use Carbon\Carbon;

function formatDateTime(
    DateTimeInterface|string|float|int $inputDateTime = null,
    string $outputFormat = 'Y-m-d H:i:s',
    DateTimeZone|string $outputTimezone = 'UTC',
    DateTimeZone|string $inputTimezone = 'UTC'
): string
{
    $carbon = is_numeric($inputDateTime)
        ? Carbon::createFromTimestamp($inputDateTime, $inputTimezone)
        : new Carbon($inputDateTime, $inputTimezone);

    return $carbon->setTimezone($outputTimezone)->format($outputFormat);
}

Let’s go over this bit by bit. The function takes 4 arguments and none of them are required which means that if called without any argument, the function should return a current UTC DateTime string in a common database format.

$date = formatDateTime();
// 2022-02-03 08:10:21

First argument $inputDateTime is the most important one and by its signature you can easily figure out that it can accept various DateTime formats including a string, float, integer and a DateTimeInterface capable object. That last one is important because it enables us to work with any PHP DateTime object as well as any potential library that implements that interface (such as Carbon).

// string
$date = formatDateTime('2022-02-03 08:10:21');

// string
$date = formatDateTime('2022-12-31');

// int (UNIX timestamp)
$date = formatDateTime(time());

// float (UNIX timestamp in microseconds)
$date = formatDateTime(microtime(true));

// DateTime object
$date = formatDateTime(new DateTime);

// Carbon object
$date = formatDateTime(new Carbon);

// Laravel Carbon datetime casting
$date = formatDateTime($post->created_at);

Other arguments are pretty self-explanatory.

$outputFormat controls in which format will function return the DateTime string, e.g.:

$date = formatDateTime(new DateTime, 'd/m/Y');
// 03/02/2022

$outputTimezone controls the result timezone and $inputTimezone tells the function in which timezone is the $inputDateTime.

If you’re running under PHP8+ then it’s even easier to handle arguments with the “named arguments” feature like so:

$date = formatDateTime(
    inputTimezone: 'Europe/Zagreb'
);

We’re available for partnerships and open for new projects. If you want to know more about us, click here.
Also, don’t forget to follow us on Instagram and Facebook