PHP
if (!function_exists('toUserDate')) {
function toUserDate(string|Carbon $date, ?User $user = null, string $timezone = 'UTC'): string
{
if ($user) {
$timezone = $user->timezone;
}
if (is_string($date)) {
return Carbon::parse($date, 'UTC')->setTimezone($timezone)->isoFormat('L');
}
return $date->setTimezone($timezone)->isoFormat('L');
}
}
This code defines a custom helper function called toUserDate
in a Laravel 8.0 application. This function is intended to format a date for display in the user’s timezone.
Let’s break down the code:
PHP
if (!function_exists('toUserDate')) {
function toUserDate(string|Carbon $date, ?User $user = null, string $timezone = 'UTC'): string
{
// Check if the function toUserDate doesn't already exist
// This is to avoid conflicts if the function is defined elsewhere
// (e.g., in another part of the code or a package)
if ($user) {
// If a User object is provided, use the user's timezone
$timezone = $user->timezone;
}
if (is_string($date)) {
// If $date is a string, parse it into a Carbon instance and set the timezone
return Carbon::parse($date, 'UTC')->setTimezone($timezone)->isoFormat('L');
}
// If $date is already a Carbon instance, set the timezone and format it
return $date->setTimezone($timezone)->isoFormat('L');
}
}
Here’s what each part of the code does:
if (!function_exists('toUserDate')) { ... }
: Checks if the functiontoUserDate
does not already exist. This is a good practice to prevent conflicts if the function is defined elsewhere.function toUserDate(string|Carbon $date, ?User $user = null, string $timezone = 'UTC'): string
: Defines thetoUserDate
function. It takes three parameters:$date
: Either a string representing a date or aCarbon
instance.$user
: An optional parameter representing the user for whom the date should be formatted. It defaults tonull
.$timezone
: An optional parameter representing the timezone to be used. It defaults to'UTC'
.
if ($user) { ... }
: Checks if a$user
object is provided. If so, it sets the$timezone
variable to the user’s timezone.if (is_string($date)) { ... }
: Checks if$date
is a string. If so, it parses the string into aCarbon
instance, sets the timezone, and formats it using the ISO format ‘L’.- The
return
statement at the end formats the$date
(either string orCarbon
instance) based on the provided$timezone
and returns it as a string using the ISO format ‘L’.
In summary, the toUserDate
function is a convenient utility for formatting dates according to a specified timezone, and optionally, for a specific user’s timezone.