I’m trying to use JavaScript to convert a date object into a valid MySQL date – what is the best way to do this?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Update: Here in 2021, Date.js hasn’t been maintained in years and is not recommended, and Moment.js is in "maintenance only" mode. We have the built-in
Intl.DateTimeFormat,Intl.RelativeTimeFormat, and (soon)Temporalinstead, probably best to use those. Some useful links are linked from Moment’s page on entering maintenance mode.Old Answer:
Probably best to use a library like Date.js (although that hasn’t been maintained in years) or Moment.js.
But to do it manually, you can use
Date#getFullYear(),Date#getMonth()(it starts with 0 = January, so you probably want + 1), andDate#getDate()(day of month). Just pad out the month and day to two characters, e.g.:Usage:
Note that the function has a name, which is useful for debugging purposes, but because of the anonymous scoping function there’s no pollution of the global namespace.
That uses local time; for UTC, just use the UTC versions (
getUTCFullYear, etc.).Caveat: I just threw that out, it’s completely untested.