Created
May 1, 2024 11:37
-
-
Save codeeshop-oc/e8c53e45415a07d6cdaec41166a2ca9d to your computer and use it in GitHub Desktop.
Get Random Dates for number of times in format YYYY-MM-DD HH:MM:SS from last two years
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 getRandomDates(numDates) { | |
const twoYearsAgo = new Date(); | |
twoYearsAgo.setFullYear(twoYearsAgo.getFullYear() - 2); | |
const today = new Date(); | |
const dates = []; | |
for (let i = 0; i < numDates; i++) { | |
// Get random milliseconds between two years ago and today | |
const randomTime = twoYearsAgo.getTime() + Math.random() * (today.getTime() - twoYearsAgo.getTime()); | |
const randomDate = new Date(randomTime); | |
// Format the date as YYYY-MM-DD HH:MM:SS | |
const formattedDate = randomDate.toISOString().slice(0, 19).replace('T', ' '); | |
dates.push(formattedDate); | |
} | |
return dates; | |
} | |
// Aim for around 64 dates, but ensure at least 1 | |
const numDates = 64 | |
const desiredDates = Math.max(numDates, Math.floor(Math.random() * 10) + 55); | |
const randomDatesArray = getRandomDates(desiredDates); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment