How do I get a timestamp in JavaScript?

Here are more detailed examples of working with timestamps in JavaScript, covering different scenarios and edge cases:

1. Basic Timestamp Methods

Current timestamp (milliseconds since Unix Epoch):

// Preferred method (modern and efficient)
const timestamp1 = Date.now();

// Using Date object methods
const timestamp2 = new Date().getTime();
const timestamp3 = new Date().valueOf();

// Short syntax (implicit conversion)
const timestamp4 = +new Date();

console.log(timestamp1); // e.g., 1717300000000

2. Timestamp for a Specific Date

// From a date string
const date1 = new Date("2024-05-20").getTime();
console.log(date1); // 1716163200000 (midnight UTC)

// From individual components
const date2 = new Date(2024, 4, 20, 15, 30).getTime(); // Month is 0-indexed (May = 4)
console.log(date2); // Timestamp for May 20, 2024 15:30:00 (local time)

// From UTC components
const dateUTC = Date.UTC(2024, 4, 20, 15, 30);
console.log(dateUTC); // UTC-based timestamp (no timezone offset)

3. Parsing Dates from Strings

const parsedDate = Date.parse("2024-05-20T12:00:00Z"); // ISO 8601 format
console.log(parsedDate); // 1716206400000 (UTC timestamp)

4. Timezone Awareness

UTC vs Local Time:

const localTime = new Date(2024, 4, 20).getTime(); // Local timezone offset applied
const utcTime = Date.UTC(2024, 4, 20); // Ignores local timezone
console.log(localTime !== utcTime); // True (difference depends on your timezone)

5. Convert Timestamp to Seconds

const ms = Date.now();
const seconds = Math.floor(ms / 1000); // For APIs expecting Unix time in seconds
console.log(seconds); // e.g., 1717300000

6. Invalid Dates

const invalidDate = new Date("invalid-date-string").getTime();
console.log(invalidDate); // NaN (Not-a-Number)

7. Reverse Engineering (Timestamp to Date)

const timestamp = 1717300000000;
const date = new Date(timestamp);
console.log(date.toISOString()); // "2024-06-01T12:46:40.000Z"

8. Performance Measurement

const start = Date.now();
// Simulate work
for (let i = 0; i < 1e6; i++) {}
const end = Date.now();
console.log(`Elapsed time: ${end - start}ms`);

9. Edge Cases

Leap Years/Milliseconds:

const leapYearDate = new Date("2024-02-29").getTime(); // Valid leap year
console.log(leapYearDate); // 1709164800000 (Feb 29, 2024 UTC)

Min/Max Dates:

console.log(new Date(-8640000000000000).getTime()); // Minimum valid timestamp (-273,790 BCE)
console.log(new Date(8640000000000000).getTime()); // Maximum valid timestamp (+275,760 CE)

10. Alternative: performance.now()

// High-resolution timing (milliseconds since page load, not Unix Epoch)
const perfTime = performance.now();
console.log(perfTime); // e.g., 1234.56 (used for precise benchmarks)

Key Takeaways

Use CaseMethod
Current timestampDate.now()
Specific datenew Date(...).getTime()
UTC-based timestampDate.UTC()
Parse from stringDate.parse()
Convert to secondsMath.floor(Date.now() / 1000)
High-resolution timingperformance.now()

When to Use What

  • General timestamps: Date.now() or new Date().getTime().
  • API/backend interactions: Convert to seconds if required.
  • Timezone-sensitive operations: Use Date.UTC() or getTimezoneOffset().
  • Invalid dates: Always validate with !isNaN(timestamp).

Leave a Reply

Your email address will not be published. Required fields are marked *