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

bawa_geek

Lakh Bawa

Posted on August 11, 2020

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
💖 💪 🙅 🚩
bawa_geek
Lakh Bawa

Posted on August 11, 2020

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

Sign up to receive the latest update from our blog.

Related