Last active
October 9, 2024 22:10
-
-
Save miguelmota/5b67e03845d840c949c4 to your computer and use it in GitHub Desktop.
Random date in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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())) |
very useful! thanks.
good vibes to you!
Thank you!
Good job, but i don't understand, how it's work.... Please explain)))
@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:
- You get the number of miliseconds between end and start dates.
- You multiply the result by Math.random()
- 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) - 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
Thanks man!