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
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.
The day of the month. Single-digit days will have a leading zero. The abbreviated name of the day of the week.
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 .
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"
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With