Skip to content

Instantly share code, notes, and snippets.

@ericyd
Last active April 30, 2018 19:39
Show Gist options
  • Save ericyd/3b87f1789f87d1a10d3bbcfc17cd751d to your computer and use it in GitHub Desktop.
Save ericyd/3b87f1789f87d1a10d3bbcfc17cd751d to your computer and use it in GitHub Desktop.
/**
* Takes a date object and returns a string in the form YYYY-MM-DD
* e.g. formatDate(newDate()) should return 2017-02-17 for February 17, 2017.
*
* @param {date} d the date object to be formatted
*/
function formatDate (d = new Date()) {
// explain:
// | YYYY format | add leading 0 to Jan-Sep | month is 0-indexed | add leading 0 to days 1-9 | day of month
return `${d.getFullYear() }-${ d.getMonth() < 9 ? '0' : '' }${ d.getMonth() + 1 }-${ d.getDate() < 10 ? '0' : '' }${ d.getDate()}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment