Reputation: 8111
I have a javascript date object and want to format it like this
2014-12-18
like %Y-%m-%d
but I can't seem to find a "good way to achieving this at once. Why does javascript not have a strftime function? How can I achieve what I want?
Upvotes: 3
Views: 3446
Reputation: 305
Based on helpermethod's answer, here is a way to do it with 0-padded months and dates:
function pad(num) {
return (num >= 10 ? '' : '0') + num;
}
const now = new Date();
const s = now.getFullYear() + '-' + pad(now.getMonth() + 1) + '-' + pad(now.getDate());
alert(s); // 2020-04-08
Upvotes: 1
Reputation: 62244
No need to use an external library:
var now = new Date();
var s = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
alert(s); // 2014-12-18
Explanation:
getFullYear()
gives you the 4-digit year
getMonth()
gives you the month (0-based, that's why you have to add 1)
getDate()
gives you the day of month
Upvotes: 7
Reputation: 410
Did you try Moment.js ?
Install
bower install moment --save # bower
npm install moment --save # npm
Install-Package Moment.js # NuGet
Format Dates
moment().format('MMMM Do YYYY, h:mm:ss a'); // December 18th 2014, 2:08:59 pm
moment().format('dddd'); // Thursday
moment().format("MMM Do YY"); // Dec 18th 14
moment().format('YYYY [escaped] YYYY'); // 2014 escaped 2014
moment().format(); // 2014-12-18T14:08:59+01:00
Here is the docs
Upvotes: 1
Reputation: 5316
You can use library moment
. There is no good reason behind lack of Date formatting functions.
This answer contains code to format date as %Y-%m-%d
in vanilla JS.
Upvotes: 1