Question
How can I get the current time in milliseconds in JavaScript, similar to Java's System.currentTimeMillis()?
For example, in Java you can write:
System.currentTimeMillis()
What is the JavaScript equivalent for getting the current time in milliseconds?
Short Answer
By the end of this page, you will understand how JavaScript represents time, how to get the current timestamp in milliseconds, and when to use Date.now() versus new Date().getTime(). You will also see common mistakes, real-world use cases, and a small project that uses timestamps in practice.
Concept
JavaScript stores dates and times using the Date object. Internally, a JavaScript date is based on the number of milliseconds since the Unix epoch, which is:
1970-01-01T00:00:00Z
When people ask for the "current time in milliseconds," they usually mean the current Unix timestamp in milliseconds.
In JavaScript, the most direct way to get that value is:
Date.now()
This returns a number such as:
1718012345678
That number is useful because it is:
- Easy to compare
- Easy to store in databases
- Useful for measuring elapsed time
- Common in logs, APIs, and caching systems
Before Date.now() became common, developers often used:
new Date().getTime()
This produces the same kind of value, but it first creates a Date object and then extracts its timestamp.
In real programming, timestamps matter whenever you need to answer questions like:
- When did something happen?
- How long did something take?
- Has this cached data expired?
- Which event happened first?
So the core concept is not just "getting the time" but understanding that JavaScript time is often handled as a numeric timestamp in milliseconds.
Mental Model
Think of time in JavaScript like a giant stopwatch that started at midnight UTC on January 1, 1970.
Every millisecond since that starting point increases the counter by 1.
Date.now()asks: What number is the stopwatch showing right now?new Date()creates a full date object, like a calendar clock you can inspect..getTime()asks that date object for its stopwatch number.
So if you only need the number, Date.now() is the simpler tool. If you need a full date object for formatting or extracting parts like year or month, new Date() is useful.
Syntax and Examples
The two most common ways to get the current time in milliseconds are:
Date.now()
and
new Date().getTime()
Example 1: Recommended approach
const timestamp = Date.now();
console.log(timestamp);
This prints the current Unix timestamp in milliseconds.
Example 2: Older but still valid approach
const timestamp = new Date().getTime();
console.log(timestamp);
This gives the same type of result.
Example 3: Measuring elapsed time
const start = Date.now();
// Simulate some work
for ( i = ; i < ; i++) {
}
end = .();
.();
Step by Step Execution
Consider this example:
const start = Date.now();
const result = 5 + 3;
const end = Date.now();
console.log(result);
console.log(end - start);
Step by step:
-
const start = Date.now();- JavaScript gets the current timestamp in milliseconds.
- Example value:
1718012345000
-
const result = 5 + 3;- JavaScript calculates the value
8.
- JavaScript calculates the value
-
const end = Date.now();- JavaScript gets the current timestamp again.
- Example value:
1718012345001
-
console.log(result);- Prints
Real World Use Cases
Getting the current time in milliseconds is common in many practical situations.
Logging events
console.log(`[${Date.now()}] User logged in`);
Useful for debugging and tracking program behavior.
Cache expiration
const expiresAt = Date.now() + 60_000;
This sets an expiration time 60 seconds in the future.
Measuring performance
const start = Date.now();
// run task
const duration = Date.now() - start;
Useful in scripts, APIs, and backend services.
Sorting events by time
const events = [
{ id: 1, createdAt: 1718012000000 },
{ id: 2, : }
];
Real Codebase Usage
In real projects, developers use timestamps as simple numeric values because they are easy to compare and store.
Validation and guard clauses
function isExpired(expiresAt) {
return Date.now() > expiresAt;
}
This is a common pattern in authentication, caching, and session handling.
Early returns
function canRetry(lastAttemptTime) {
if (Date.now() - lastAttemptTime < 5000) {
return false;
}
return true;
}
This keeps logic simple and readable.
API payloads
const payload = {
userId: 42,
createdAt: Date.now()
};
Many systems send timestamps as numbers rather than formatted date strings.
Error and event tracking
Common Mistakes
1. Forgetting the parentheses on Date.now
Broken code:
const time = Date.now;
console.log(time);
This stores the function itself, not the current timestamp.
Correct version:
const time = Date.now();
console.log(time);
2. Confusing milliseconds with seconds
JavaScript Date.now() returns milliseconds, not seconds.
const ms = Date.now();
const seconds = Math.floor(Date.now() / 1000);
If an API expects seconds, divide by 1000.
3. Using formatted date strings when a numeric timestamp is better
Less convenient:
Comparisons
| Approach | Returns | Best use | Notes |
|---|---|---|---|
Date.now() | Current timestamp in milliseconds | Getting current time as a number | Shortest and clearest |
new Date().getTime() | Current timestamp in milliseconds | When you already have a Date object pattern | Slightly more verbose |
new Date() | A Date object | Formatting or extracting date parts | Not just a number |
performance.now() | High-resolution elapsed time | Performance measurement in browsers | Not a Unix timestamp |
Cheat Sheet
// Current time in milliseconds
Date.now();
// Equivalent older style
new Date().getTime();
// Convert milliseconds to seconds
Math.floor(Date.now() / 1000);
// Measure elapsed time
const start = Date.now();
// ...code...
const duration = Date.now() - start;
// Create Date object from timestamp
const date = new Date(Date.now());
Key rules
- JavaScript timestamps are usually milliseconds since 1970-01-01 UTC.
Date.now()returns a number.new Date()returns a Date object.- Use
getTime()to get milliseconds from aDateobject. - Be careful not to confuse milliseconds with .
FAQ
What is the JavaScript equivalent of System.currentTimeMillis()?
Use Date.now(). It returns the current time in milliseconds since the Unix epoch.
Is Date.now() the same as new Date().getTime()?
Yes. Both return the current timestamp in milliseconds. Date.now() is just shorter and clearer.
Does JavaScript return time in seconds or milliseconds?
Date.now() returns milliseconds. If you need seconds, divide by 1000 and usually round or floor the result.
Can I use new Date() by itself?
Yes, but it returns a Date object, not a numeric timestamp. Use .getTime() if you need milliseconds.
What does the timestamp start from?
It starts from the Unix epoch: 1970-01-01T00:00:00Z.
Should I use Date.now() to measure performance?
For general timing, yes. For more precise benchmarking in browsers, performance.now() is often better.
Why are timestamps useful in APIs and databases?
Mini Project
Description
Build a simple JavaScript utility that tracks when a task starts and ends, then prints how long the task took in milliseconds. This demonstrates how current timestamps are used for timing operations in real programs.
Goal
Create a small timer that records a start time, an end time, and the total duration in milliseconds.
Requirements
- Record the current time when the task starts.
- Simulate some work in the program.
- Record the current time again when the task ends.
- Calculate the duration by subtracting the start time from the end time.
- Print the start time, end time, and duration.
Keep learning
Related questions
Accessing Cargo Package Metadata in Rust
Learn how to read Cargo package metadata like version, name, and authors in Rust using compile-time environment macros.
Associated Types vs Generic Type Parameters in Rust: When to Use Each
Learn when to use associated types vs generic parameters in Rust traits, with clear rules, examples, and practical API design advice.
Can a Struct Extend Another Struct in Rust? Composition vs Inheritance
Learn how Rust handles struct reuse without inheritance, using composition, traits, and wrapper structs with practical examples.