Skip to content

Instantly share code, notes, and snippets.

@callezenwaka
Last active July 9, 2021 05:09
Show Gist options
  • Save callezenwaka/8b5074c4071f33edd280e721f3d684a5 to your computer and use it in GitHub Desktop.
Save callezenwaka/8b5074c4071f33edd280e721f3d684a5 to your computer and use it in GitHub Desktop.
Number Padding In JavaScript
// Define new date, result
let d = new Date(), result;
// Set new date
d.setDate(d.getDate() + 20);
// Return result
result = ('0' + d.getDate()).slice(-2) + '/' + ('0' + (d.getMonth()+1)).slice(-2) + '/' + d.getFullYear();
Explanation:
.slice(-2) returns the last 2 characters of the string.
if the d.getMonth() returns 9, .slice(-2) returns ("0" + "9") as "09" which is the last 2 characters.
i.e: ("0" + "9").slice(-2) => "09"
However, if d.getMonth() returns 10, .slice(-2) returns ("0" + "10") as "10".
i.e: ("0" + "10").slice(-2) => "10"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment