-2

I need to express a Date as a String with the exact format format:

 2015-01-20   

I see there is an date.toIsoFormatString() but not sure where or how to provide the format shown above.

 Here is my code:

 var future = new Date();
 future.setDate(future.getDate() + 30);
 console.log(future);

Now I want future.toString() or future.toIsoFormatString() to display the date in just the YYYY-MM-DD format.

Get Smarter
  • 181
  • 2
  • 2
  • 9
  • 2
    And any of [these answers](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) or the [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) couldn't solve your problem? – Teemu Jan 30 '15 at 22:51
  • No Teemu. No console.log(future.toString('yyyy-MM-dd')); taken directly from this answer yields: Sun Mar 01 2015 15:01:59 GMT-0800 (PST), but if you can think of an answer please post it. – Get Smarter Jan 30 '15 at 23:03
  • No? Just keep digging ... ; ) – Teemu Jan 30 '15 at 23:06
  • www.stackoverflow.com --> www.justkeepdigging.com ? :) – Get Smarter Jan 30 '15 at 23:12
  • Guess I've had too much Vodka ... – Get Smarter Jan 30 '15 at 23:14
  • Well, I could have boiled it down to four letters (RTFM), I thought the dig stuff would be nicer to read. Btw. please be careful with the Vodka ... – Teemu Jan 30 '15 at 23:30

2 Answers2

6

IE>8 and all other updated browsers can do this natively-

new Date().toISOString().slice(0,10);
kennebec
  • 102,654
  • 32
  • 106
  • 127
  • *toISOString* uses UTC, whereas the OP appears to want the local date. This will produce the wrong local date for the period of the timezone offset adjacent to midnight. – RobG Jul 24 '19 at 20:35
4

You can use momentJs library for formated date.

Example without momentJs :

 myDate = new Date();
 myDate.getFullYear() + "-" + (myDate.getMonth()+1) + "-" + myDate.getDate() // 2015-1-31

Example with momentJs :

moment().format("YYYY-MM-DD") // 2015-01-31

MomentJs have many others useful function

Karim BENHDECH
  • 371
  • 2
  • 9