Skip to content

Instantly share code, notes, and snippets.

@jamesdaily
Created October 24, 2023 14:04
Show Gist options
  • Save jamesdaily/b44993f7a43a1a68702af3145309cdfe to your computer and use it in GitHub Desktop.
Save jamesdaily/b44993f7a43a1a68702af3145309cdfe to your computer and use it in GitHub Desktop.
randomDateOfBirth JavaScript function for generating sample DOB within an age range
function assert(condition, message) {
if (!condition) {
throw new Error("Assertion failed: [" + (message || "no message") + "]" );
}
}
function randomDate(start, end) {
assert(start < end,"start < end");
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
function randomDateOfBirth(minAge = 0, maxAge = 121, asOfDate = new Date()) {
assert(minAge>=0,"minAge>=0");
assert(maxAge<=999,"maxAge<=999");
assert(minAge<=maxAge,"minAge<=maxAge");
var d = randomDate(new Date( asOfDate.getFullYear()-maxAge , 0, 1), new Date(asOfDate.getFullYear()-minAge, 11, 31));
d.setHours(0,0,0,0); //optionally adjust datetime to midnight local time
return d;
}
//Usage:
const random_dob = randomDateOfBirth(18,65);
console.log("Date with time and tz:",random_dob.toISOString()); //"Date with time and tz:", "1947-05-19T00:00:00.000Z"
console.log("Date only:",random_dob.toISOString().slice(0,10)); //"Date only:", "1947-05-19"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment