Created
February 23, 2022 20:18
-
-
Save inanepain/73945167ce879624830d21451f62f700 to your computer and use it in GitHub Desktop.
Function has option for short date (Ymd) and to change the divider for short date.
This file contains hidden or 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
/** | |
* Get random date between two dates | |
* | |
* @param {Date} start earliest date | |
* @param {Date} [end=today] latest date | |
* @param {boolean} [short=false] only get Ymd (as string) | |
* @param {string} [join='-'] divider for short date | |
* | |
* @returns {Date|string} | |
*/ | |
function randomDate(start, end = new Date(), short = false, join = '-') { | |
const d = new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); | |
if (short) { | |
let year = d.getFullYear(), | |
month = '' + (d.getMonth() + 1), | |
day = '' + d.getDate(); | |
if (month.length < 2) month = '0' + month; | |
if (day.length < 2) day = '0' + day; | |
return [year, month, day].join(join); | |
} | |
return d; | |
} | |
const startDate = new Date(2012, 0, 1); | |
const endDate = new Date(2020, 11, 31); | |
console.log("between: 2010-01-01, and: today\n\t=>\t", randomDate(startDate)); | |
console.log("\nbetween: 2010-01-01, and: 2020-12-31\n\t=>\t", randomDate(startDate, endDate)); | |
console.log("\nbetween: 2010-01-01, and: 2020-12-31, as: short\n\t=>\t", randomDate(startDate, endDate, true)); | |
console.log("\nbetween: 2010-01-01, and: 2020-12-31, as: short, divider: none\n\t=>\t", randomDate(startDate, endDate, true, '')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment