3

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?

dthree
  • 19,847
  • 14
  • 77
  • 106
Apostolos
  • 7,763
  • 17
  • 80
  • 150

4 Answers4

8

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

helpermethod
  • 59,493
  • 71
  • 188
  • 276
  • 2
    Be aware that getMonth and getDate can be 1-digit so you'll need to optionally pad it with a '0' if you want dates like 2014-01-09 instead of 2014-1-9 – matsve Apr 08 '20 at 13:46
1

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

Alaa-GI
  • 410
  • 1
  • 5
  • 19
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Darin Kolev Dec 18 '14 at 11:26
  • 1
    I gave directly the link because in the official website there is everything you need about moment.js, but i agree with you it's better to give answer here ;) – Alaa-GI Dec 18 '14 at 13:18
  • FYI moment is a pretty large dependency. There are newer lighter alternatives like https://date-fns.org/ or https://github.com/moment/luxon – Sean William Washington Jun 05 '18 at 17:31
1

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.

Community
  • 1
  • 1
Ginden
  • 5,149
  • 34
  • 68
1

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
matsve
  • 297
  • 4
  • 11