31

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
  • 868
  • 2
  • 11
  • 24
  • 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
  • 7
    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

14 Answers14

87

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,923
  • 1
  • 27
  • 26
leaksterrr
  • 3,800
  • 7
  • 34
  • 65
  • 15
    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
  • 3
    Warning! Since this method converts the date to UTC, the resulting string will stubbornly be plus or minus a day depending on your timezone and the time of day. So it's annoyingly not the best solution. – JakeMc Apr 28 '22 at 01:23
12

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
Starfish
  • 3,344
  • 1
  • 19
  • 47
8

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
  • 7,460
  • 6
  • 69
  • 114
7

One line solution for 'YYYY-MM-DD'

new Date().toLocaleDateString("fr-CA", {year:"numeric", month: "2-digit", day:"2-digit"})

// output on New Years Eve 2023: '2023-12-31'

devupper
  • 71
  • 1
  • 2
  • the most elegant one I've seen – mWang Mar 15 '23 at 02:14
  • Looks like you can just use `new Date().toLocaleDateString("en-CA")` .. you can also specify a timezone to change the date to a local one somewhere else, e.g. `new Date().toLocaleDateString("en-CA", { timeZone: "Australia/Sydney"})` – som Jul 10 '23 at 07:42
5

By using Moment.js library, you can do:

var datetime = new Date("2015-09-17 15:00:00");
datetime = moment(datetime).format("YYYY-MM-DD");
Rafael Tavares
  • 5,678
  • 4
  • 32
  • 48
usman tahir
  • 273
  • 4
  • 4
2
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));
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
  • 11,616
  • 6
  • 48
  • 84
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

This will convert a unix timestamp to local date (+ time)

function UnixTimeToLocalDate = function( unix_epoch_time )
{
    var date,
        str;
        
    date = new Date( unix_epoch_time * 1000 );
    
    str = date.getFullYear() + '-' +
          (date.getMonth() + 1 + '').padStart( 2, '0' )  + '-' +
          (date.getDate() + '').padStart( 2, '0' );

    // If you need hh:mm:ss too then

    str += ' ' +
          (date.getHours()   + '').padStart( 2, '0' ) + ':' +
          (date.getMinutes() + '').padStart( 2, '0' ) + ':' +
          (date.getSeconds() + '').padStart( 2, '0' );
          
    return str;
}
Paolo
  • 15,233
  • 27
  • 70
  • 91
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
  • 359
  • 3
  • 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

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
  • 11,616
  • 6
  • 48
  • 84
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
  • 1,001
  • 8
  • 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.

tylerwillis
  • 109
  • 1
  • 8
0

If you want a text format that's good for sorting use:

function formatDateYYYYMMDDHHMMSS(date){
  // YYYY-MM-DD HH:MM:SS
  const datePart = date.toISOString().split("T")[0]
  const timePart = date.toLocaleString('en-US', {hour12: false}).split(",")[1]
  return datePart + timePart
}

As prototype:

Date.prototype.toSortString = function(){
  const date = new Date(this.valueOf());
  return date.toISOString().split("T")[0] + 
         date.toLocaleString('en-US', {hour12: false}).split(",")[1]
}
kztd
  • 3,121
  • 1
  • 20
  • 18
  • This won't work consistently unless your timezone is GMT, because `toISOString` converts from local to UTC time. – Auspex Nov 04 '22 at 13:21
-1

const padTo2Digits = num => {
  return num.toString().padStart(2, '0')
}

const formatDate = date => {
  return [
    date.getFullYear(),
    padTo2Digits(date.getMonth() + 1),
    padTo2Digits(date.getDate())
  ].join('-')
}

let value = formatDate(new Date())

document.getElementById('dayFormatUS').innerHTML = value

const transformDate = date => {
  const convert = date.split('-').reverse()
  return convert.join('/')
}

document.getElementById('dayFormatBR').innerHTML = transformDate(value)
<div>
  Format US - 
  <span id='dayFormatUS'></span>
</div>

<div>
  Format BR - 
  <span id='dayFormatBR'></span>
</div>