getMilliseconds()

ES1+

Returns the milliseconds component of the given date according to local time, as an integer from 0 to 999. It exposes only the sub-second digits of the wall-clock breakdown; the full epoch-relative millisecond count comes from getTime() or Date.now() instead.

Syntax

date.getMilliseconds()

Return Value

number

A number (0-999) representing the milliseconds

Examples

JavaScript
const date = new Date();
console.log(date.getMilliseconds());
Output:
// 123

📌 When to Use

Use getMilliseconds() when you specifically need the sub-second digits of a timestamp: rendering log lines as 14:30:45.123, adding millisecond precision to custom time formats, debugging event ordering in the console, or generating a display that distinguishes events within the same second. It is a component extractor like getSeconds(), which means the value on its own is almost never useful; it acquires meaning only next to the hour, minute, and second it accompanies. Keep it clearly separated from two near neighbors. getTime() returns the entire millisecond offset since the epoch and is what you want for arithmetic, storage, and comparison; getMilliseconds() returns just the final three digits of the wall-clock representation. And performance.now() provides high-resolution, monotonic timing for measurement, with microsecond-scale precision (subject to browser coarsening) that Date can never offer. A reasonable secondary use is as a low-cost entropy sprinkle in non-critical identifiers, distinguishing IDs minted within the same second, but treat that strictly as a collision-reducer rather than a uniqueness guarantee: bursts of activity routinely produce several events in one millisecond, and only counters or crypto.randomUUID() actually guarantee distinctness.

⚠️ Common Mistakes

Using getMilliseconds() to measure elapsed time. Subtracting two milliseconds components wraps at 1000 and says a 2.3-second operation took 300 ms. Durations come from getTime() or performance.now() differences; the component getter is for display digits only.

Treating a timestamp-plus-milliseconds string as a unique ID. Two clicks, two requests, or a tight loop easily mint identical values in the same millisecond, and collisions corrupt keyed data silently. Append a counter or random suffix, or use crypto.randomUUID().

Expecting sub-millisecond information: getMilliseconds() is an integer 0-999, and the underlying Date only stores whole milliseconds. Microsecond-scale measurements require performance.now(), and even that is intentionally coarsened by browsers as a side-channel mitigation.

Forgetting three-digit padding in composed timestamps, so 14:30:45.7 appears instead of 14:30:45.007; milliseconds need padStart(3, "0"), one more digit than the other components.

Assuming event timestamps have true millisecond fidelity. Timer callbacks are clamped (nested setTimeout has a minimum of about 4 ms; hidden tabs throttle to a second or more), so millisecond components of scheduled events reflect scheduler behavior more than real-world timing.

✅ Best Practices

For log timestamps, prefer toISOString(), which already includes zero-padded milliseconds in a sortable, timezone-unambiguous format; hand-composed formats should be reserved for cases where the ISO shape genuinely does not fit.

Pad to three digits whenever you do compose manually: String(d.getMilliseconds()).padStart(3, "0"). Unpadded milliseconds destroy the lexicographic sortability that makes text timestamps useful in log pipelines.

Generate IDs with the right tool for the guarantee you need: crypto.randomUUID() for global uniqueness, a monotonic counter for per-session ordering, and timestamp-based prefixes only for human-readable sortability, as in the example below.

Measure code with performance.now() and mark real-world instants with Date: the former is monotonic and high-resolution, the latter is meaningful across machines. A function that mixes both roles in one number is a design smell.

When migrating to Temporal, note that Temporal.Instant and PlainTime expose millisecond, microsecond, and nanosecond fields separately; code that parses digits out of formatted strings to recover precision becomes unnecessary.

⚡ Performance Notes

getMilliseconds() is a constant-time read of the cached component breakdown, indistinguishable in cost from getSeconds(); call frequency is never a concern. The relevant performance facts sit nearby. Date only resolves to whole milliseconds, so busy systems generating many events per millisecond cannot rely on it for ordering, and sorting by such timestamps needs a secondary tiebreaker (a counter) to remain stable. Browsers deliberately reduce timer resolution, so both Date.now() and event.timeStamp may quantize to coarser steps under site isolation policies, which is invisible to most apps but matters for fine-grained instrumentation. Finally, ID-generation schemes that format timestamp strings per call are dominated by string allocation, not by the getter; in hot paths, keep IDs numeric as long as possible and format lazily.

🌍 Real World Example

Unique Transaction ID Generator

Support teams and payment logs benefit from IDs that both sort chronologically and remain human-readable, and the timestamp-plus-suffix pattern here delivers that: the date and time components give instant context, the millisecond digits separate same-second events, and a random suffix handles same-millisecond collisions. This is a pragmatic middle ground between opaque UUIDs and fragile bare timestamps, common in order numbers and trace IDs. The example also demonstrates the padding discipline every component-based format needs to stay sortable as text.

function generateTransactionId(prefix = 'TXN') {
  const now = new Date();
  const timestamp = now.getFullYear().toString() +
    String(now.getMonth() + 1).padStart(2, '0') +
    String(now.getDate()).padStart(2, '0') +
    String(now.getHours()).padStart(2, '0') +
    String(now.getMinutes()).padStart(2, '0') +
    String(now.getSeconds()).padStart(2, '0') +
    String(now.getMilliseconds()).padStart(3, '0');

  const random = Math.random().toString(36).substr(2, 4).toUpperCase();

  return `${prefix}-${timestamp}-${random}`;
}

console.log(generateTransactionId()); // "TXN-20240315143025123-X7K2"

Related Methods