0

I am trying to generate a random date between two dates, could you check the below code?

What i notice is the output as : 02.0/01.0/1918.0

How can i save it as 02/02/1918 instead of 02.0/01.0/1918.0

var dob;

//set a range of years
var min = 1900;
var max = 2004;

// Math.ceil prevents the value from being 0;
var month = Math.ceil(Math.random() * 12);
var day = Math.ceil(Math.random() * 28);
var year = Math.floor(Math.random() * (max - min) + min);

//this ensures that the format will stay mm/dd/yyyy;
if(month < 10) {
    month = "0" + month;
}
if(day < 10) {
    day = "0" + day;
}

//concatenates random dob in mm/dd/yyyy format;
dob = month + "/" + day + "/" + year;

return dob;
bbb
  • 149
  • 2
  • 18
  • be careful with the random numbers, they are zero-based. you must add 1 to the random() * 12, otherwise you get incorrect values. for example, if the random number is 0, multiplied by 12 you get also 0, but to get first month, you need to add 1. same logic applies for days and years. – Catalin Aug 29 '21 at 21:52

1 Answers1

0

Math.floor returns double. You have to convert it to int.

var year = Math.floor(...) as int
daggett
  • 26,404
  • 3
  • 40
  • 56