Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero Padding a Date with JavaScript

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

like image 603
Vaibhav Jain Avatar asked May 02 '13 17:05

Vaibhav Jain


1 Answers

This is what you could to. Just see if the date is bigger than 9. If so use it, if not add a leading zero

var curr_date = d.getDate();
curr_date = curr_date > 9 ? curr_date : "0" + curr_date;
like image 172
SirDerpington Avatar answered Oct 08 '22 09:10

SirDerpington