Apostolos
Apostolos

Reputation: 8111

Why isn't there a standard way to format a date object in javascript?

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

Answers (4)

matsve
matsve

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

helpermethod
helpermethod

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

Alaa-GI
Alaa-GI

Reputation: 410

Did you try Moment.js ?

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

Ginden
Ginden

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

Related Questions