1

I have tried this code but it gives me the date in the wrong format:

function randomDate(start, end) {
    return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}

randomDate(new Date(2012, 0, 1), new Date())

returns a date like this

Fri Dec 16 1988 06:20:22 GMT+0000 (GMT Standard Time)

How would i change it to the "yyyy-mm-dd" format? so for example

1985-09-22
Yasmin French
  • 1,154
  • 3
  • 12
  • 25

5 Answers5

8

try with this code, this will help you.

function randomDate(start, end) {
    var d = new Date(start.getTime() + Math.random() * (end.getTime() -                     start.getTime())),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
}
Raju Detroja
  • 132
  • 6
1

You need to parse javascript date object to the format you need. You can do it like this:

function randomDate(start, end) {
    return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())).toISOString().slice(0,10);
}

randomDate(new Date(2012, 0, 1), new Date())
Evt.V
  • 179
  • 4
0

You have two options here:

  • Build the date string on you own by concatenating specific parts of your date (eg. using date.getMonth() and similar methods.
  • Format the date using designated library, eg. Moment.js
mdziekon
  • 3,531
  • 3
  • 22
  • 32
0

Use following code :

var date =randomDate(new Date(2012, 0, 1), new Date());
var formattedDate =date.getFullYear()+'-' + (date.getMonth()+1) + '-'+date.getDate();
Abhijeet
  • 4,069
  • 1
  • 22
  • 38
0

If you don't need a general purpose function, just put it together

var d = new Date();
alert(
    ("00" + (d.getMonth() + 1)).slice(-2) + "/" + 
    ("00" + d.getDate()).slice(-2) + "/" + 
    d.getFullYear() + " " + 
    ("00" + d.getHours()).slice(-2) + ":" + 
    ("00" + d.getMinutes()).slice(-2) + ":" + 
    ("00" + d.getSeconds()).slice(-2)
);
Bela Vizy
  • 1,133
  • 8
  • 19