Skip to content

Instantly share code, notes, and snippets.

@Remzi1993
Created December 3, 2021 14:52
Show Gist options
  • Save Remzi1993/4eca8cfbc5eb7d1d9250e139f8bd98b9 to your computer and use it in GitHub Desktop.
Save Remzi1993/4eca8cfbc5eb7d1d9250e139f8bd98b9 to your computer and use it in GitHub Desktop.
JavaScript date examples with leading zeroes to date
// Create or parse a new date
let date = new Date();
// YYYY-MM-DD
let dateFormat1 = date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + date.getDate()).slice(-2);
// DD-MM-YYYY
let dateFormat2 = ('0' + date.getDate()).slice(-2) + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + date.getFullYear();
// Log
console.log(dateFormat1);
console.log(dateFormat2);
// Parse a SQL date
let date2 = new Date('2015-03-04T00:00:00.000Z');
// YYYY-MM-DD
let dateFormat3 = date2.getFullYear() + '-' + ('0' + (date2.getMonth() + 1)).slice(-2) + '-' + ('0' + date2.getDate()).slice(-2);
// DD-MM-YYYY
let dateFormat4 = ('0' + date2.getDate()).slice(-2) + '-' + ('0' + (date2.getMonth() + 1)).slice(-2) + '-' + date2.getFullYear();
// Log
console.log(dateFormat3);
console.log(dateFormat4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment