Tue, Apr 23, 2019 1:56 PM

Hi guys, today I want to share a snippet I used to parse date. This snippet is written in Php and has Carbon dependencies.

The function in this snippet can receive either date in string form or Carbon object. In case of anything happen, this function will return null. This function also are able to convert date to any specified timezone.

The reason I wrote this function is because I don't want to deal with null value that come from legacy database, also any exception that come when date provided is not in correct form or sometimes when I don't know the date original format.

<?php


namespace App\Core;


use Carbon\Carbon;
use Exception;


class CustomDate
{
    public static function parse($date, $date_format = null, $timezone = 'UTC', $return_format = 'Y-m-d H:i:s', $return_timezone = 'UTC') 
    {        
        $temp_date = $date;
        if (!$temp_date) {
            return null;
        }
        
        if (!( $temp_date instanceof Carbon )) {
            if ($temp_date <= 0) {
                return null;
            }


            if ($date_format && $timezone) {
                try {
                    $temp_date = Carbon::createFromFormat($date_format, $temp_date, $timezone)
                    ->setTimezone($return_timezone);
                } catch (Exception $e) {
                    return null;
                }
            } else {
                try {
                    $temp_date = Carbon::parse($temp_date)->timezone($timezone);
                } catch (Exception $e) {
                    return null;
                }
            }
        }


        $temp_date = $temp_date->timezone($return_timezone);


        switch ($return_format) {
            case 'object':
                return $temp_date;
            case 'raw':
                return $date;
                break;
            case 'toDayDateTimeString':
                return $temp_date->toDayDateTimeString();
                break;
            case 'toFormattedDateString':
                return $temp_date->toFormattedDateString();
                break;
            default:
                return $temp_date->format($return_format);
                break;
        }
    }
}

// Usage
CustomDate::parse('2019-04-22', 'Y-m-d', 'UTC', 'toFormattedDateString', 'Asia\Kuala Lumpur');
// result: Apr 22, 2019