14

Normally if I wanted to get the date I could just do something like

var d = new Date(); console.log(d);

The problem with doing that, is when I run that code, it returns:

Mon Aug 24 2015 4:20:00 GMT-0800 (Pacific Standard Time)

How could I get the Date() method to return a value in a "MM-DD-YYYY" format so it would return something like:

8/24/2015

Or, maybe MM-DD-YYYY H:M

8/24/2016 4:20

OneStig
  • 619
  • 2
  • 9
  • 22
  • 3
    I recommend using http://momentjs.com/ for all of your javascript date needs, it makes everything much easier. – house9 Aug 24 '15 at 22:47
  • 2
    possible duplicate of [How to format a JavaScript date](http://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – Felipe Oriani Aug 24 '15 at 22:47
  • 4
    In _UTC_, `d.toISOString().split('T')[0]` – Paul S. Aug 24 '15 at 22:47
  • I think you can find your answer here:- [How to get current formatted date dd/mm/yyyy in Javascript and append it to an input. ][1] [1]: http://stackoverflow.com/questions/12409299/how-to-get-current-formatted-date-dd-mm-yyyy-in-javascript-and-append-it-to-an-i – Raef Kandil Aug 24 '15 at 22:59
  • What about `d.toLocaleDateString()`? That will give you exactly the result in your first example. – cezar Jan 28 '18 at 08:15
  • 1
    I can't believe such a simple request could not be solved by Javascript native function. – Zhang Buzz Oct 09 '18 at 10:08

10 Answers10

57

Just use the built-in .toISOString() method like so: toISOString().split('T')[0]. Simple, clean and all in a single line.

var date = (new Date()).toISOString().split('T')[0];
document.getElementById('date').innerHTML = date;
<div id="date"></div>

Please note that the timezone of the formatted string is UTC rather than local time.

Leksat
  • 2,549
  • 1
  • 24
  • 25
leaksterrr
  • 3,292
  • 6
  • 29
  • 61
  • 12
    This probably needs a note that the result will be in _UTC (GMT+0000)_, not the client's local timezone (such as _GMT-0700_) – Paul S. Aug 24 '15 at 22:56
10

The below code is a way of doing it. If you have a date, pass it to the convertDate() function and it will return a string in the YYYY-MM-DD format:

var todaysDate = new Date();

function convertDate(date) {
  var yyyy = date.getFullYear().toString();
  var mm = (date.getMonth()+1).toString();
  var dd  = date.getDate().toString();

  var mmChars = mm.split('');
  var ddChars = dd.split('');

  return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}

console.log(convertDate(todaysDate)); // Returns: 2015-08-25
Patrick2607
  • 3,071
  • 1
  • 13
  • 37
5

Yet another way:

var today = new Date().getFullYear()+'-'+("0"+(new Date().getMonth()+1)).slice(-2)+'-'+("0"+new Date().getDate()).slice(-2)
document.getElementById("today").innerHTML = today
<div id="today">
DevonDahon
  • 4,134
  • 2
  • 37
  • 57
2

What you want to achieve can be accomplished with native JavaScript. The object Date has methods that generate exactly the output you wish.
Here are code examples:

var d = new Date();
console.log(d);
>>> Sun Jan 28 2018 08:28:04 GMT+0000 (GMT)
console.log(d.toLocaleDateString());
>>> 1/28/2018
console.log(d.toLocaleString());
>>> 1/28/2018, 8:28:04 AM

There is really no need to reinvent the wheel.

cezar
  • 9,952
  • 5
  • 35
  • 74
1
function formatdate(userDate){
  var omar= new Date(userDate);
  y  = omar.getFullYear().toString();
  m = omar.getMonth().toString();
  d = omar.getDate().toString();
  omar=y+m+d;
  return omar;
}
console.log(formatDate("12/31/2014"));
cezar
  • 9,952
  • 5
  • 35
  • 74
Omar Khaiyam
  • 13
  • 1
  • 2
  • 2
    Please add explanation. Code only answer isn't really very helpful. – cezar Jan 28 '18 at 08:11
  • This code does not work and has two issues: It will not produce the yyyy-mm-dd format because you're not adding leading zeroes to years, months nor dates. test it when your date is "0001-01-01". Your month will always be decreased by 1 because Date.getMonth() returns 0 for January. – ErroneousFatality Oct 15 '20 at 15:21
1

By using moment.js library, you can do it:

var datetime = new Date("2015-09-17 15:00:00"); datetime = moment(datetime).format("YYYY-MM-DD");

usman tahir
  • 89
  • 1
  • 4
1
var today = new Date();

function formatDate(date) {
 var dd = date.getDate();
        var mm = date.getMonth() + 1; //January is 0!
        var yyyy = date.getFullYear();
        if (dd < 10) {
          dd = '0' + dd;
        }
        if (mm < 10) {
          mm = '0' + mm;
        }
        //return dd + '/' + mm + '/' + yyyy;
             return yyyy + '/' + mm + '/' +dd ;

}

console.log(formatDate(today));
0

If you are trying to get the 'local-ISO' date string. Try the code below.

function (date) {
    return new Date(+date - date.getTimezoneOffset() * 60 * 1000).toISOString().split(/[TZ]/).slice(0, 2).join(' ');
}

+date Get milliseconds from a date.

Ref: Date.prototype.getTimezoneOffset Have fun with it :)

Fisher
  • 213
  • 2
  • 5
  • This is just asking for a problem on DST boundaries (and other, even weirder quirks of certain timezones/locales). – Ry- Jan 08 '18 at 12:11
0

Here is a simple function I created when once I kept working on a project where I constantly needed to get today, yesterday, and tomorrow's date in this format.

function returnYYYYMMDD(numFromToday = 0){
  let d = new Date();
  d.setDate(d.getDate() + numFromToday);
  const month = d.getMonth() < 9 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1;
  const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
  return `${d.getFullYear()}-${month}-${day}`;
}

console.log(returnYYYYMMDD(-1)); // returns yesterday
console.log(returnYYYYMMDD()); // returns today
console.log(returnYYYYMMDD(1)); // returns tomorrow

Can easily be modified to pass it a date instead, but here you pass a number and it will return that many days from today.

Lou Bagel
  • 551
  • 4
  • 11
  • Also is missing the leading zero adding to year, because someone could be using a year that has less than 4 digits. – ErroneousFatality Oct 15 '20 at 15:23
  • 1
    @ErroneousFatality good point, but as I prefaced in my answer this is an example how I grabbed the date for today/tomorrow/yesterday/etc. So unless OP is a time traveler... – Lou Bagel Oct 15 '20 at 15:44
0

If you're not opposed to adding a small library, Date-Mirror (NPM or unpkg) allows you to format an existing date in YYYY-MM-DD into whatever date string format you'd like.

date('n/j/Y', '2020-02-07') // 2/7/2020
date('n/j/Y g:iA', '2020-02-07 4:45PM') // 2/7/2020 4:45PM
date('n/j [until] n/j', '2020-02-07', '2020-02-08') // 2/7 until 2/8

Disclaimer: I developed Date-Mirror.