Date.now()

ES5+

Returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.

Syntax

Date.now()

Return Value

number

A number representing the milliseconds elapsed since the UNIX epoch

Examples

JavaScript
console.log(Date.now());
// μ„±λŠ₯ 츑정에 유용
const start = Date.now();
// ... μž‘μ—… μˆ˜ν–‰
const end = Date.now();
console.log('μ†Œμš” μ‹œκ°„:', end - start, 'ms');
Output:
// 1705123456789 μ†Œμš” μ‹œκ°„: 5 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

Related Methods