Date.now()
ES5+Returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.
Syntax
Date.now()Return Value
A number representing the milliseconds elapsed since the UNIX epoch
Examples
console.log(Date.now());
// μ±λ₯ μΈ‘μ μ μ μ©
const start = Date.now();
// ... μμ
μν
const end = Date.now();
console.log('μμ μκ°:', end - start, 'ms'); π When to Use
Use Date.now() for performance measurement, generating unique IDs, rate limiting, cache expiration, or any scenario requiring a current timestamp.
β οΈ Common Mistakes
Using new Date().getTime() instead of Date.now() - Date.now() is more efficient as it does not create a Date object.
Relying on Date.now() for high-precision timing when performance.now() is more appropriate.
β Best Practices
Use Date.now() for timestamps that need to be stored or compared across sessions.
For high-precision performance measurement in browsers, use performance.now() instead.
β‘ Performance Notes
Date.now() is highly optimized and faster than new Date().getTime(). It does not allocate a Date object, making it ideal for frequently called code paths.
π Real World Example
API Rate Limiter
Implement a simple rate limiter to prevent too many API calls within a time window.
class RateLimiter {
constructor(maxRequests, timeWindowMs) {
this.maxRequests = maxRequests;
this.timeWindowMs = timeWindowMs;
this.requests = [];
}
canMakeRequest() {
const now = Date.now();
// Remove expired timestamps
this.requests = this.requests.filter(
time => now - time < this.timeWindowMs
);
if (this.requests.length < this.maxRequests) {
this.requests.push(now);
return true;
}
return false;
}
}
const limiter = new RateLimiter(5, 60000); // 5 requests per minute
console.log(limiter.canMakeRequest()); // true
console.log(limiter.canMakeRequest()); // true