getMilliseconds()

ES1+

Returns the milliseconds (0-999) in the specified date according to local time.

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() for high-precision timing displays, animation synchronization, or unique ID generation requiring millisecond components.

⚠️ Common Mistakes

Using getMilliseconds() for timing measurements - use Date.now() or performance.now() instead.

✅ Best Practices

For logging timestamps, use toISOString() which includes milliseconds automatically.

⚡ Performance Notes

getMilliseconds() is O(1). For sub-millisecond precision, use performance.now() instead.

🌍 Real World Example

Unique Transaction ID Generator

Generate unique transaction IDs using timestamp with millisecond precision.

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