0
0
JavascriptHow-ToBeginner · 3 min read

How to Get Current Time in JavaScript: Simple Guide

Use the Date object in JavaScript to get the current time. For example, new Date() creates a date object with the current date and time, and Date.now() returns the current time in milliseconds since January 1, 1970.
📐

Syntax

The main ways to get the current time in JavaScript are:

  • new Date(): Creates a new date object with the current date and time.
  • Date.now(): Returns the current time as the number of milliseconds since January 1, 1970 (Unix epoch).

You can then use methods like getHours(), getMinutes(), and getSeconds() on the date object to get specific parts of the time.

javascript
const now = new Date();
const timestamp = Date.now();
💻

Example

This example shows how to get the current time and display it in hours, minutes, and seconds.

javascript
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();

console.log(`Current time is ${hours}:${minutes}:${seconds}`);
Output
Current time is 14:30:45
⚠️

Common Pitfalls

One common mistake is to call Date() without new, which returns a string instead of a date object. Another is forgetting that Date.now() returns milliseconds, so you may need to convert it to seconds or a date object for easier use.

javascript
/* Wrong way: returns string, not Date object */
const wrong = Date();
console.log(typeof wrong); // "string"

/* Right way: creates Date object */
const right = new Date();
console.log(typeof right); // "object"
Output
string object
📊

Quick Reference

MethodDescriptionReturns
new Date()Creates a date object with current date and timeDate object
Date.now()Returns current time in milliseconds since 1970-01-01Number (milliseconds)
getHours()Gets the hour from a Date object (0-23)Number
getMinutes()Gets the minutes from a Date object (0-59)Number
getSeconds()Gets the seconds from a Date object (0-59)Number

Key Takeaways

Use new Date() to get the current date and time as an object.
Use Date.now() to get the current time in milliseconds since 1970.
Extract hours, minutes, and seconds from a Date object using getHours(), getMinutes(), and getSeconds().
Always use new with Date() to get a Date object, not a string.
Remember Date.now() returns milliseconds, so convert if needed.