JavaScript Date.now() function
The Date.now()
function in JavaScript returns the current timestamp in milliseconds since the Unix Epoch (January 1, 1970, 00:00:00 UTC). Unlike the new Date()
constructor, Date.now()
returns a number, not a Date
object.
Syntax:
Explanation:
Date.now()
gives the number of milliseconds that have passed since January 1, 1970.- This is often used to measure time intervals or calculate time differences.
Example:
Output:
Explanation:
- The output will be a large number representing the current timestamp in milliseconds (this will differ depending on when the code is executed).
Use Cases:
1. Calculating Time Differences
You can use Date.now()
to measure how long an operation takes by storing the current timestamp at the start and end of the operation.
Output:
Explanation:
Date.now()
is called before and after a time-consuming operation to measure how long it took in milliseconds.
2. Creating a Unique ID Based on Time
You can use Date.now()
to generate unique identifiers for events or records based on the current timestamp.
Output:
Summary:
Date.now()
returns the current timestamp as the number of milliseconds since January 1, 1970.- It is useful for time-based calculations, performance measurements, and generating unique timestamps.
- Unlike
new Date()
, it does not return aDate
object, but instead, a raw millisecond timestamp.