Skip to content

Instantly share code, notes, and snippets.

@UziTech
Created August 8, 2014 04:14
Show Gist options
  • Save UziTech/f8af14f07c89c7a25dde to your computer and use it in GitHub Desktop.
Save UziTech/f8af14f07c89c7a25dde to your computer and use it in GitHub Desktop.
Format date as mySQL date format
/**
* DWTFYW License
*
* Author: Tony Brix, http://tonybrix.info
*
* Formats date in mm/dd/yyyy format as yyyy-mm-dd
*
* Returns false on failure
*
*/
function mysqlDate(date) {
var m, d, y;
if (/\d{2}\/\d{2}\/\d{4}/.test(date)) {//format: mm/dd/yyyy
var temp = date.split("/");
m = parseInt(temp[0]);
d = parseInt(temp[1]);
y = parseInt(temp[2]);
} else if (/\d{4}-\d{2}-\d{2}/.test(date)) {//format: yyyy-mm-dd
var temp = date.split("-");
y = parseInt(temp[0]);
m = parseInt(temp[1]);
d = parseInt(temp[2]);
} else {
return false;
}
var testDate = new Date(y, m - 1, d);
if (testDate.getFullYear() === y && testDate.getMonth() + 1 === m && testDate.getDate() === d) {
return y + "-" + m + "-" + d;
} else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment