Formatting JavaScript date for MySQL database insertion through PHP and AJAX

I’m working on a web application where I need to send a date from JavaScript to PHP using AJAX, then store it in a MySQL database. The problem is that I keep getting date format errors when trying to insert the data.

I’ve tried different approaches like sending the date object directly, converting it to JSON format, and using UTC conversion. But MySQL keeps rejecting the date format.

The specific error message I receive is:

Invalid date format: ‘Mon, 15 Mar 1985 08:30:00 GMT’ for column ‘user_birthdate’

Everything else in my code works perfectly. I can update all other database fields without issues. It’s only the date field that’s causing problems.

Here’s how I create the date in JavaScript:

var birthDate = new Date(selectedYear, selectedMonth, selectedDay, selectedHour, selectedMinute, 0, 0);

My AJAX request looks like this:

var updateRequest = jQuery.ajax({
    url: app_path + "save_profile.php",
    data: { 'user_id': this.userId,
            'birth_date': this.birthDate.toUTCString(),
            ... },
    type: 'POST',
    datatype: 'json',
    success: function(response, status) {
        ...
    },
    error: function (xhr, options, error) {
        ...
    }
});

And here’s my PHP database query:

$query = "UPDATE user_profile 
SET prof_gender = '".$user_gender."',
    prof_diet_plan = (SELECT plan_id FROM diet_plans WHERE plan_name = '".$user_diet."'),
    prof_activity_level = (SELECT level_id FROM activity_levels WHERE level_name = '".$user_activity."'),
    prof_birth_date = '".$user_birthdate."'
WHERE prof_user_id = ".$user_id;

What’s the correct way to format the date so MySQL will accept it?

Had this exact headache six months ago. Yeah, toUTCString() is a pain with that verbose format. I stopped fighting JavaScript and moved the conversion to PHP instead. Just send the timestamp with getTime() (gives you milliseconds since epoch), then use date(‘Y-m-d H:i:s’, $timestamp/1000) in PHP to get MySQL format. Kills timezone issues and format problems completely. Side note - your SQL query’s wide open to injection. Use prepared statements with PDO or mysqli instead of jamming strings together.

toUTCString() spits out that weird format MySQL can’t stand. Use toISOString().split(‘T’)[0] instead - you’ll get YYYY-MM-DD which MySQL actually likes. Or just handle it in PHP with the date() function.

This is a super common issue with JS and MySQL date formats. Don’t use toUTCString() - it’s way too verbose. Use toISOString() instead and slice it down: this.birthDate.toISOString().slice(0, 19).replace('T', ' ') gets you YYYY-MM-DD HH:MM:SS for MySQL DATETIME fields. Just need the date? Use .slice(0, 10). You could also let PHP do the heavy lifting with DateTime::createFromFormat() or strtotime() - they’ll parse different formats and spit out MySQL-ready strings. Plus you get better control over edge cases that way.