Generate Random Dates in JavaScript
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: JavaScript
What: Generate random dates in JavaScript for frontend and Node.js applications. Covers Date objects, date ranges, formatting with moment.js and date-fns, and timezone handling.
Try it: Use our interactive Dates generator or integrate this code into your JavaScript application.
Generate random dates in JavaScript for frontend and Node.js applications. Covers Date objects, date ranges, formatting with moment.js and date-fns, and timezone handling. Looking for other languages? Check our code examples in PHP , Python , Java , C# , C++ , Ruby and Go or use our interactive web generator.
JavaScript Code Example
// Generate random date between two dates
function randomDate(startDate, endDate) {
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
const randomTimestamp = Math.floor(Math.random() * (end - start + 1)) + start;
return new Date(randomTimestamp);
}
// Generate random date as ISO string
function randomDateISO(startDate, endDate) {
return randomDate(startDate, endDate).toISOString().split("T")[0];
}
// Generate random past date (within last N days)
function randomPastDate(daysAgo = 365) {
const now = new Date();
const past = new Date(now.getTime() - Math.random() * daysAgo * 86400000);
return past;
}
// Generate random future date (within next N days)
function randomFutureDate(daysAhead = 365) {
const now = new Date();
const future = new Date(now.getTime() + Math.random() * daysAhead * 86400000);
return future;
}
// Generate random birthday (18-80 years ago)
function randomBirthday() {
const now = new Date();
const minAge = 18;
const maxAge = 80;
const minDate = new Date(now.getFullYear() - maxAge, now.getMonth(), now.getDate());
const maxDate = new Date(now.getFullYear() - minAge, now.getMonth(), now.getDate());
return randomDate(minDate, maxDate);
}
// Format date as YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}
// Generate multiple random dates
function generateRandomDates(count = 10, startDate = "2020-01-01", endDate = "2025-12-31") {
return Array.from({length: count}, () =>
formatDate(randomDate(startDate, endDate))
);
}
// Using moment.js (npm install moment)
// const moment = require("moment");
// const randomMoment = moment(Math.random() * (
// moment("2025-12-31").valueOf() - moment("2020-01-01").valueOf()
// ) + moment("2020-01-01").valueOf());
// Using date-fns (npm install date-fns)
// const { addDays, subDays } = require("date-fns");
// const pastDate = subDays(new Date(), Math.floor(Math.random() * 365));
// const futureDate = addDays(new Date(), Math.floor(Math.random() * 365));
// Usage examples
console.log("Random date:", formatDate(randomDate("2020-01-01", "2025-12-31")));
console.log("Past date:", formatDate(randomPastDate(30)));
console.log("Future date:", formatDate(randomFutureDate(90)));
console.log("Random birthday:", formatDate(randomBirthday()));
console.log("ISO format:", randomDateISO("2020-01-01", "2025-12-31"));
console.log("Batch:", generateRandomDates(5));
[EXPLANATION]
JavaScript's Date object uses milliseconds since Unix epoch. getTime() returns milliseconds, and Math.random() generates values between the range. The toISOString() method outputs ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ). Month indexes are 0-based (0=January, 11=December). Libraries like moment.js and date-fns provide timezone support, localization, and convenient manipulation methods. 86400000 milliseconds = 1 day.
Expected Output
Random date: 2023-07-15 Past date: 2024-11-17 Future date: 2025-03-15 Random birthday: 1985-04-23 ISO format: 2023-07-15 Batch: [ "2022-03-12", "2024-08-05", "2021-11-28", "2023-05-19", "2025-01-07" ]
Common Use Cases
- Generate test dates for frontend calendar components
- Create mock API responses with realistic timestamps
- Populate date pickers with sample data for UI testing
- Test date filtering and sorting in React/Vue/Angular apps
- Generate time-series data for chart visualizations
Important Notes
- JavaScript Date months are 0-indexed: January=0, December=11
-
getTime()returns milliseconds since Jan 1, 1970 UTC -
For timezone handling, use
toLocaleString()or libraries like Luxon - moment.js is in maintenance mode; consider date-fns or Luxon for new projects
-
new Date().toISOString()always outputs UTC timezone
Try Our Interactive Generator
Don't want to write code? Use our free web-based Dates generator with instant results.
TRY DATES GENERATOR →Other Programming Languages
View Dates generation code examples in PHP
View Dates generation code examples in Python
View Dates generation code examples in Java
View Dates generation code examples in C#
View Dates generation code examples in C++
View Dates generation code examples in Ruby
View Dates generation code examples in Go