Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript date - Leading 0 for days and months where applicable

Tags:

Is there a clean way of adding a 0 in front of the day or month when the day or month is less than 10:

var myDate = new Date(); var prettyDate =(myDate.getFullYear() +'-'+ myDate.getMonth()) +'-'+ myDate.getDate(); 

This would output as:

2011-8-8 

I would like it to be:

2011-08-08 
like image 606
Harry Avatar asked Aug 08 '11 08:08

Harry


People also ask

Why are months zero indexed in JS?

because they might have an array of string (indexed from 0) of month names and these month numbers if they start from 0, it'll be lot easier to map to the month strings.. Show activity on this post.

Should dates have leading zeros?

The day of the month. Single-digit days will have a leading zero. The abbreviated name of the day of the week.

What date format is dd mm yyyy in JavaScript?

To format a date as dd/mm/yyyy: Use the getDate() , getMonth() and getFullYear() methods to get the day, month and year of the date. Add a leading zero to the day and month digits if the value is less than 10 .


2 Answers

The format you seem to want looks like ISO. So take advantage of toISOString():

var d = new Date(); var date = d.toISOString().slice(0,10); // "2014-05-12" 
like image 54
mivk Avatar answered Jan 01 '23 21:01

mivk


No, there is no nice way to do it. You have to resort to something like:

var myDate = new Date();  var year = myDate.getFullYear();  var month = myDate.getMonth() + 1; if(month <= 9)     month = '0'+month;  var day= myDate.getDate(); if(day <= 9)     day = '0'+day;  var prettyDate = year +'-'+ month +'-'+ day; 
like image 36
Paul Avatar answered Jan 01 '23 22:01

Paul