Creating a Neat DateTime Helper Function in PHP

rcerljenko

Ricardo Čerljenko

Posted on March 24, 2022

Creating a Neat DateTime Helper Function in PHP

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 (eg. 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 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);
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

$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'
);
Enter fullscreen mode Exit fullscreen mode

Thank you for reading this! If you've found this interesting, consider leaving a ❤️, 🦄 , and of course, share and comment on your thoughts!

Lloyds is available for partnerships and open for new projects. If you want to know more about us, check us out.

Also, don’t forget to follow us on Instagram and Facebook!

💖 💪 🙅 🚩
rcerljenko
Ricardo Čerljenko

Posted on March 24, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related