DEV Community

Cover image for How to parse and format JavaScript-based DataTime String for MySQL DateTime fields
Lakh Bawa
Lakh Bawa

Posted on

How to parse and format JavaScript-based DataTime String for MySQL DateTime fields

It took me long to figure out the things to parse JavaScript DateTime string into PHP, I am sharing my work here so you don't have to struggle for it

    if (!function_exists('convertJSTimeToDBTime')) {
        /**
         * @param string $timestring
         * @param bool $convertToUTC
         * @param string $format
         * @return string
         * @throws Exception
         */
        function convertJSTimeToDBTime(string $timestring, $convertToUTC = false, $format = 'd-m-Y H:i:s'): string
        {

            $date = Carbon::parse(date_create_from_format('D M d Y H:i:s e+', $timestring));
                if ($convertToUTC) {
                    $date->tz('UTC');
                }
                return $date->format($format);
        }
    }

Enter fullscreen mode Exit fullscreen mode

Top comments (0)