Question

How to Get the Current Time in Milliseconds in JavaScript

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.

Take Quiz

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 (let i = 0; i < 1000000; i++) {
  // do something
}

const end = Date.now();
console.log(`Elapsed: ${end - start} ms`);

This subtracts the starting timestamp from the ending timestamp to measure duration.

Example 4: Creating a date from a timestamp

const timestamp = Date.now();
const date = new Date(timestamp);

console.log(date);

This is useful when you store a number first and convert it back to a readable date later.

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:

  1. const start = Date.now();

    • JavaScript gets the current timestamp in milliseconds.
    • Example value: 1718012345000
  2. const result = 5 + 3;

    • JavaScript calculates the value 8.
  3. const end = Date.now();

    • JavaScript gets the current timestamp again.
    • Example value: 1718012345001
  4. console.log(result);

    • Prints 8
  5. console.log(end - start);

    • Subtracts the two timestamps
    • Result might be 1
    • That means the code took about 1 millisecond

The exact numbers will vary each time you run the code.

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, createdAt: 1718013000000 }
];

Timestamps make sorting straightforward.

Rate limiting or cooldowns

if (Date.now() - lastClickTime < 1000) {
  console.log('Please wait before clicking again');
}

Useful in games, forms, and UI interactions.

Take Quiz

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

function logError(message) {
  return {
    message,
    timestamp: Date.now()
  };
}

This helps with debugging across distributed systems.

Comparing timestamps

if (user.updatedAt > user.createdAt) {
  console.log('User record was updated');
}

Numeric comparisons are much easier than comparing formatted date strings.

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:

const time = new Date().toString();

Better for comparisons:

const time = Date.now();

Strings are harder to compare and parse.

4. Assuming Date.now() is for high-precision benchmarking

Date.now() is fine for general timing, but not ideal for very precise performance measurements in all environments.

For example, in browsers developers often use performance.now() for more precise elapsed-time measurement.

5. Mixing Date objects and numbers without noticing

Broken code:

const createdAt = new Date();
const age = Date.now() - createdAt;

This may work because JavaScript converts the date object to a number, but it can be confusing for beginners.

Clearer version:

const createdAt = Date.now();
const age = Date.now() - createdAt;

Or:

const createdAt = new Date();
const age = Date.now() - createdAt.getTime();

Comparisons

ApproachReturnsBest useNotes
Date.now()Current timestamp in millisecondsGetting current time as a numberShortest and clearest
new Date().getTime()Current timestamp in millisecondsWhen you already have a Date object patternSlightly more verbose
new Date()A Date objectFormatting or extracting date partsNot just a number
performance.now()High-resolution elapsed timePerformance measurement in browsersNot a Unix timestamp

Date.now() vs new Date().getTime()

  • Both return milliseconds since the Unix epoch.
  • Date.now() is usually preferred because it is simpler.
  • new Date().getTime() is still valid and widely understood.

Date.now() vs performance.now()

  • Use Date.now() when you need the current real-world timestamp.
  • Use performance.now() when you want precise elapsed time for benchmarking in supported environments.

Example:

console.log(Date.now());
console.log(performance.now());

These values mean different things, so they should not be treated as interchangeable.

Take Quiz

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 a Date object.
  • Be careful not to confuse milliseconds with seconds.

Quick memory tip

  • Need a number now? -> Date.now()
  • Need a date object? -> new Date()
  • Need the number from a date object? -> .getTime()

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?

They are compact, easy to compare, and language-independent, which makes them practical for storage and communication.

Take Quiz

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

  1. Record the current time when the task starts.
  2. Simulate some work in the program.
  3. Record the current time again when the task ends.
  4. Calculate the duration by subtracting the start time from the end time.
  5. Print the start time, end time, and duration.
Take Quiz

Keep learning

Related questions

View more