Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active October 9, 2024 22:10
Show Gist options
  • Save miguelmota/5b67e03845d840c949c4 to your computer and use it in GitHub Desktop.
Save miguelmota/5b67e03845d840c949c4 to your computer and use it in GitHub Desktop.
Random date in JavaScript
function randomDate(start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()))
}
console.log(randomDate(new Date(2012, 0, 1), new Date()))
@arthursvpb
Copy link

very useful! thanks.

@giovponce
Copy link

good vibes to you!

@Heunsig
Copy link

Heunsig commented Nov 8, 2022

Thank you!

@DidarHalla
Copy link

Good job, but i don't understand, how it's work.... Please explain)))

@Medychar
Copy link

Medychar commented Oct 9, 2024

@DidarHalla I am not a JS dev but I think that it works like this:

  • start.getTime() - you get the number of milliseconds since January 1, 1970 00:00:00 UTC for the start
  • Math.random() - you get a floating-point number greater than or equal to 0 and less than 1
  • end.GetTime() - you get the number of milliseconds since January 1, 1970 00:00:00 UTC for the end

Then this is the order of actions:

  1. You get the number of miliseconds between end and start dates.
  2. You multiply the result by Math.random()
  3. You add the result to the number of miliseconds from the start.getTime(). The result of this operation can be the same as start.getTime() (if Math.random() is zero) but it cannot be greater than end.getTime() because you multiply the difference by Math.random that is less than 1.
    (I do not know if it can be equal end.getTime() because I do not know the "scale" of roundings)
  4. You use the result as the parameter for "new Date(our result)" constructor that accepts number of milliseconds since January 1, 1970 00:00:00 UTC and uses it to create the date object.

Btw. I know that your comment is almost 2 years old but maybe it will be useful for someone else or for you if you gave up the topic :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment