Zero Padding a Date with JavaScript
javascript, jquery
Solution
You can implement this logic like:
var d = new Date();
var curr_date = ("0" + d.getDate()).slice(-2);
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
console.log( m_names[curr_month] + " " +curr_date + " " + curr_year);
FIDDLE
UPDATES - ( October 1st, 2017 )
EcmaScript 2017 or ES8 has introduced two new String prototype methods: `padStart()` and `padEnd()`. We can add some extra spaces or dashes (or any other character), before or after a string. We can utilise it here like:
var curr_date = d.getDate().toString().padStart(2,0);
( This syntax could have been shorter if we didn't need to convert d.getDate() to string, as padStart only works on string )
Demo:
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
var d = new Date('10/1/2017');
var curr_date = d.getDate().toString().padStart(2, 0);
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
var formatted_date = m_names[curr_month] + " " + curr_date + " " + curr_year;
console.log(formatted_date);
Problem
I want to format a date like this: `May 02 2013` but at the moment, my formatting looks like this: `May 2 2013` How can I zero pad this type of date so that the day in the date is something like `02` instead of just `2`? Here is the code I am using: ``` var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); var d = new Date(); var curr_date = d.getDate(); var curr_month = d.getMonth(); var curr_year = d.getFullYear(); alert( m_names[curr_month] + " " +curr_date + " " + curr_year); ``` jsFiddle code here