Skip to content

Instantly share code, notes, and snippets.

@hoyangtsai
Forked from niksumeiko/utils.numberToDay.js
Last active March 27, 2022 09:47
Show Gist options
  • Save hoyangtsai/515ee5a1e27a82b64a610a1219855e1f to your computer and use it in GitHub Desktop.
Save hoyangtsai/515ee5a1e27a82b64a610a1219855e1f to your computer and use it in GitHub Desktop.
#JavaScript function that converts a number into the #2-digits day of the month with leading zeros (01-31)
/**
* Turns a number/string to 2 digits day of the month with leading zero.
* @param {number|string} day to turn into day.
* @return {string}
*/
function numberToDay(j) {
return ('0' + j).slice(-2);
}
// Examples:
// Turning different type days into 2 digits number.
console.log( numberToDay(7) );
console.log( numberToDay('21') );
@hoyangtsai
Copy link
Author

hoyangtsai commented Aug 28, 2021

ES new feature - padStart
http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

const today = new Date();
const yyyy = today.getFullYear();
const mm = String(today.getMonth() + 1).padStart(2, '0');
const dd = String(today.getDate()).padStart(2, '0');
const fullDate = `${yyyy}/${mm}/${dd}`;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment