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:

  1. if (!function_exists('toUserDate')) { ... }: Checks if the function toUserDate does not already exist. This is a good practice to prevent conflicts if the function is defined elsewhere.
  2. function toUserDate(string|Carbon $date, ?User $user = null, string $timezone = 'UTC'): string: Defines the toUserDate function. It takes three parameters:
    • $date: Either a string representing a date or a Carbon instance.
    • $user: An optional parameter representing the user for whom the date should be formatted. It defaults to null.
    • $timezone: An optional parameter representing the timezone to be used. It defaults to 'UTC'.
  3. if ($user) { ... }: Checks if a $user object is provided. If so, it sets the $timezone variable to the user’s timezone.
  4. if (is_string($date)) { ... }: Checks if $date is a string. If so, it parses the string into a Carbon instance, sets the timezone, and formats it using the ISO format ‘L’.
  5. The return statement at the end formats the $date (either string or Carbon 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.

Leave a comment

Your email address will not be published. Required fields are marked *

Translate ยป