How to Use JavaScript to Get the Current Date and Time

December 6, 2023

Introduction

JavaScript is a lightweight programming language used for the World Wide Web. One of the uses of the JavaScript Date object is to check the date and time a visitor arrives at your website.

This guide will walk you through using JavaScript to get the current date and time.

how to use javascript to get the current date and time

Prerequisites

  • Familiarity with JavaScript (including creating, saving, and running scripts).
  • A text editor to write scripts.
  • Access to a web browser to open HTML files.

Create Date Object in JavaScript

The JavaScript Date() object helps when working with dates and times. It allows you to create and manipulate dates, representing a specific moment in time.

To create a new object with the current date and time, add the object to your script:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Demo: Current Date</h1>
<p id="p1"></p>
<script>
	var date = new Date();
	document.getElementById("p1").innerHTML = date;
</script>
</body>
</html>

Save the code as an HTML file and open it using a browser.

Creating the Date object in JavaScript.

The object shows the current date, time, and timezone.

The sections below show the methods for obtaining the individual date and time elements.

Use the Get Method to Show the Current Date in JavaScript

The get method in JavaScript is a way to access properties or retrieve values from objects by using built-in functionalities (like arrays or dates) or custom-defined getters in objects or classes. The get method can be used to retrieve the current date and time by creating an HTML file.

Follow the instructions below to obtain individual elements of date and time.

Get the Year

The currentDate.getFullYear method uses the today variable to display the 4-digit year.

Create a new HTML file and paste the following code to get the current year:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1> Demo: Current Year</h1>
<p id="year"></p>
<script>
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  document.getElementById("year").innerHTML = "Current Year: " + year;
</script>
</body>
</html>

Save the file and open it in a browser:

Getting the current year using JavaScript.

The method provides the current year extracted from the Date object.

Get the Month

The getMonth() method uses the Date object to obtain the numerical representation of the current month. By adding 1 to the result, the code adjusts the range from the default 0-11 to the conventional 1-12, displaying the current month within this modified range.

Create a new HTML file and paste the following code:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Demo: Current Month</h1>
<p id="month"></p>
<script>
  const currentDate = new Date();
  const month = currentDate.getMonth() + 1; // Adding 1 to convert the range from 0-11 to 1-12
  document.getElementById("month").innerHTML = "Current Month (1-12): " + month;
</script>
</body>
</html>

Save and open the file in a browser:

Getting the current month using JavaScript.

The output shows the current month as a numerical value.

Get the Day of the Month

The getDate() method fetches the day of a month from a given Date object and displays the numerical day (1-31).

Create an HTML file and paste the following code:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Demo: Current Date</h1>
<p id="dayOfMonth"></p>
<script>
  const currentDate = new Date();
  const dayOfMonth = currentDate.getDate();
  document.getElementById("dayOfMonth").innerHTML = "Current Day of the Month: " + dayOfMonth;
</script>
</body>
</html>

Open the file in a browser:

Getting the current day of the month using JavaScript.

The output shows the current day of the month.

Get the Day of the Week

The getDay() method fetches the day of the week from a given Date object and displays the result.

Paste the following code in a new HTML file:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Demo: Current Day</h1>
<p id="dayOfWeek"></p>
<script>
  const currentDate = new Date();
  const dayOfWeek = currentDate.getDay();
  document.getElementById("dayOfWeek").innerHTML = "Current Day of the Week (0-6): " + dayOfWeek;
</script>
</body>
</html>

Open it in a browser:

Getting the day of the current week using JavaScript.

The output shows the current day of the week as a numerical value.

Get Month, Date, and Year

Combine the commands to show the full date and time in the date in the YYYY-MM-DD format.

Create an HTML file and add the following code:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Demo: Current Date</h1>
<p id="p1"></p>
<script>
	var date = new Date();
	var current_date = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+ date.getDate();
	document.getElementById("p1").innerHTML = current_date;
</script>
</body>
</html>
Getting the current date using JavaScript.

If you prefer a different format, change the order of the commands.

Note: There is a dash between each command. This creates a dash between each segment of the date.

Display Hours, Minutes, and Seconds using JavaScript

To show the time in HH:MM:SS format, edit your script to look as follows:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Demo: Current Date</h1>
<p id="p1"></p>
<script>
	var date = new Date();
	var current_time = date.getHours()+":"+date.getMinutes()+":"+ date.getSeconds();
	document.getElementById("p1").innerHTML = current_time;
</script>
</body>
</html>
Getting the current time using JavaScript.

The output shows the current time on your system.

Note: There is a colon between each command. This places a colon between each numeric display so that it reads like a clock.

The sections below show how to get each element individually.

Get Current Hour

The getHours() method call uses the Date object to display the current hour in a 24-hour format.

Create an HTML file and paste the following code:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Demo: Current Hour</h1>
<p id="hours"></p>
<script>
  const currentDate = new Date();
  const hours = currentDate.getHours();
  document.getElementById("hours").innerHTML = "Current Hour (0-23): " + hours;
</script>
</body>
</html>
Getting the current hour using JavaScript.

The output shows the current hour.

Get Minutes of the Current Hour

The getMinutes() method also uses the Date object to extract the minutes of the current hour.

Create an HTML file and paste the code below:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Demo: Current Minutes</h1>
<p id="minutes"></p>
<script>
  const currentDate = new Date();
  const minutes = currentDate.getMinutes();
  document.getElementById("minutes").innerHTML = "Current Minutes (0-59): " + minutes;
</script>
</body>
</html>

Save the file and open it in a browser:

Getting minutes of the current hour using JavaScript.

The file outputs the current minute reading.

Get Seconds of the Current Minute

The getSeconds() method call extracts the seconds of the current minute. Paste the code below into a new HTML file:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Demo: Current Seconds</h1>
<p id="seconds"></p>
<script>
  const currentDate = new Date();
  const seconds = currentDate.getSeconds();
  document.getElementById("seconds").innerHTML = "Current Seconds (0-59): " + seconds;
</script>
</body>
</html>

Open the file:

Getting the current seconds using JavaScript.

The file outputs the seconds of the current minute.

See Date and Time in Different Timezones

Using the Date() object from the examples above outputs the system time on the machine you are currently using. By default, it uses your browser's time zone and displays the date as a full-text string, including the current day, date, time, and time zone.

To adjust a date by timezone in JavaScript, use the Date object and the toLocaleString() method. The following example script uses the Date object with toLocaleString() to display the time in different timezones:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Demo: Time in Different Timezones</h1>
<p id="easternTime"></p>
<p id="londonTime"></p>
<script>
  const date = new Date();
  // Display time in Eastern Time (New York)
  const easternTime = date.toLocaleString("en-US", { timeZone: "America/New_York", timeStyle: "long" });
  document.getElementById("easternTime").innerHTML = "Eastern Time (New York): " + easternTime;
  // Display time in London Time
  const londonTime = date.toLocaleString("en-GB", { timeZone: "Europe/London", timeStyle: "long" });
  document.getElementById("londonTime").innerHTML = "London Time: " + londonTime;
</script>
</body>
</html>

The output when opening the file is:

Showing the time in different time zones with JavaScript.

This script creates an HTML page that displays the current time in Eastern Time (New York) and London Time. It uses the toLocaleString() method with the timeZone option to specify the desired timezones and the timeStyle option to format the time display.

Turn Date and Time into a String via slice()

The slice() method is used primarily with strings and arrays to extract a portion of the content. It takes two parameters: the starting index (inclusive) and the ending index (exclusive), and returns the selected section as a new string.

The following example shows how to use slice() on the toUTCString() method to extract a specific portion of the date string:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Demo: Extracting Date and Time</h1>
<p id="extractedDateTime"></p>
<script>
  const date = new Date().toUTCString();
  const extractedDateTime = date.slice(5, 16);
  document.getElementById("extractedDateTime").innerHTML = "Extracted Date and Time: " + extractedDateTime;
</script>
</body>
</html>

Opening the file in a browser gives the following output:

Extracting the date and time using slice in JavaScript.

The code creates a Date object and then converts it into a string representation of the date and time in UTC using toUTCString(). After that, slice() extracts characters from index 5 to index 16 (excluding the character at index 16). The extracted portion represents a specific part of the date and time string.

Using the now() Method

The now() method obtains the milliseconds elapsed since the UNIX epoch and then converts the result into a date string. For example:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Demo: Using Date.now() Method</h1>
<p id="currentDate"></p>
<script>
  const time = Date.now();
  const date = new Date(time);
  const currentDate = date.toString();
  document.getElementById("currentDate").innerHTML = "Current Date and Time: " + currentDate;
</script>
</body>
</html>

Opening the file in a browser gives the following result:

Using the date.now method in JavaScript.

In this script, Date.now() retrieves the current time in milliseconds since the UNIX epoch. Then, it passes this time value to the Date object to create a new Date instance representing the current date and time. Finally, toString() is applied to the Date object to convert it into a string representation of the date and time.

Using the toJSON() Method

The toJSON() method returns a string representation of the date and time in a standardized format. It provides a YYYY-MM-DDTHH:MM:SS.MSSZ format where T separates the date from the time, and Z denotes the zero-hour offset (UTC).

The following example shows how to use the toJSON() method:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Demo: Using toJSON() Method</h1>
<p id="formattedDate"></p>
<script>
  const date = new Date().toJSON();
  document.getElementById("formattedDate").innerHTML = "Formatted Date and Time: " + date;
</script>
</body>
</html>

Open the file in a browser:

Using the toJSON method in Javascript.

The output shows a standardized string representation of the current date and time, adhering to the YYYY-MM-DDTHH:MM:SS.MSSZ format.

Using the toLocaleDateString() Method

The toLocaleDateString() method obtains a string representation of a Date object based on local conventions, considering the user's specification or default locale. This method allows customization by displaying the date in various formats, such as specific date styles or for different regions.

The following example shows the versatility of toLocaleDateString() with different usage scenarios:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Demo: Using toLocaleDateString() Method</h1>
<p id="formattedDate"></p>
<script>
  // Example a: Using the method without arguments
  const date1 = new Date().toLocaleDateString();
  document.getElementById("formattedDate").innerHTML += "Date without arguments: " + date1 + "<br>";
  // Example b: Using a specific locale code
  const date2 = new Date().toLocaleDateString("en-IN");
  document.getElementById("formattedDate").innerHTML += "Date with locale 'en-IN': " + date2 + "<br>";
  // Example c: Customizing the date using options
  const date = new Date();
  const options = {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  };
  const date3 = date.toLocaleDateString('en-IN', options);
  document.getElementById("formattedDate").innerHTML += "Customized Date: " + date3;
</script>
</body>
</html>

Open the file in a browser:

Using the toLocaleDateString method to show differently formatted dates.

The output shows the current date without arguments, with arguments, and a customized output.

Using Moment.js

Moment.js is a robust JavaScript library designed to simplify working with dates and times in JavaScript. It allows users to parse, manipulate, validate, and format dates in various ways and easily handle complex date-related operations and formatting tasks through its powerful API.

The Moment.js library can be downloaded and referenced locally or via a CDN link. We will use a CDN link for this tutorial.

The example below shows how Moment.js obtains and formats the current date:

<!DOCTYPE html>
<html>
<head>
  <title>Moment.js Demo</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
</head>
<body>
  <h1>Demo: Using Moment.js</h1>
  <p id="formattedDate"></p>
  <script>
    // Get the current date using Moment.js
    var date = moment();
    var currentDate = date.format('DD/MM/YYYY');
    document.getElementById("formattedDate").innerHTML = "Current Date using Moment.js: " + currentDate;
  </script>
</body>
</html>

Save the file and open it in a browser:

Using Moment.js in JavaScript to show the current date.

The output shows the current date acquired via Moment.js.

Show Full Current Date and Time in JavaScript

Combine the commands above to show the full date and time in the YYYY-MM-DD and HH:MM:SS formats. Edit your script as follows:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Demo: Current Date</h1>
<p id="p1"></p>
<script>
	var date = new Date();
	var current_date = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+ date.getDate();
	var current_time = date.getHours()+":"+date.getMinutes()+":"+ date.getSeconds();
	var date_time = current_date+" "+current_time;	
	document.getElementById("p1").innerHTML = date_time;
</script>
</body>
</html>

The final line combines the two other pieces of code. This instructs the system to display the full date next to the full time.

Showing the full current date and time via JavaScript.

Conclusion

You should now be able to write a simple piece of JavaScript to retrieve the current date and time. Such scripts can be useful for creating a timestamp by linking this script with an action and writing it into a log file.

If you're working with Python, check out our tutorial on how to get the current date and time in Python.

Next, see how to build a Node.js app with Docker, or learn to use package.json to manage a project's metadata and dependencies.

Was this article helpful?
YesNo
Bosko Marijan
Having worked as an educator and content writer, combined with his lifelong passion for all things high-tech, Bosko strives to simplify intricate concepts and make them user-friendly. That has led him to technical writing at PhoenixNAP, where he continues his mission of spreading knowledge.
Next you should read
How to Check Python Version in Linux, Mac, & Windows
December 15, 2023

Python is a popular programming language with different versions organized by release date. Certain...
Read more
Linux File Permission Tutorial: How to Check and Change Permissions
May 15, 2024

The file permission feature specifies how much power each user has over a given file or directory. To...
Read more
22 Best Linux Text Editors for Programming & Coding
August 8, 2024

A text editor is an application that lets you type text. All Linux distributions come with built-in editors...
Read more
How To Install and Use PHP Composer on Ubuntu
September 5, 2024

Composer is an application that tracks dependencies for a project, allowing you to specify a set of libraries...
Read more