Tutorials Tonight
Follow Us

JavaScript Date: A Complete Guide


In this tutorial, we are going to learn how we get and use Date in javascript. We will learn how to get the current date, year, month, day, hour, minute, etc.

Introduction To JavaScript Date

JavaScript Date is an object that represents a date and time in the JavaScript programming language.

A JavaScript Date object is a point in time, represented as the number of milliseconds since midnight January 1, 1970 UTC.

JavaScript Date objects are always in local time even though they are stored in UTC.

The Date object provides methods to fetch time, date, month, day, year and lots of other properties.

The time value in the core of the Date object is UTC, the basic method to fetch date and time all works on the local time zone.

javascript date

Here is a digital clock that shows the current date and time using the JavaScript Date object.


year: ?
month: ?
day: ?
hour: ?
minute: ?
second: ?

Create A Date Object

The Date object in javascript is created using the Date() constructor with different arguments. It returns a Date object.

new Date()

There are 4 different ways by which you can create Date object in javascript.

  1. new Date()
  2. new Date(milliseconds)
  3. new Date(dateString)
  4. new Date(year, month, day, hours, minutes, seconds, milliseconds)

1. new Date()

The new Date() method creates a new Date object representing the current date and time.

Example

// Creating date object
var today = new Date();
console.log(today);
▶ Try it

2. new Date(milliseconds)

The second method of creating a date object is new Date(milliseconds). This method return date and time passed after given milliseconds elapsed from midnight 1 January 1970 UTC.

Example

// 0 seconds after midnight 1 January 1970 UTC
var date = new Date(0);
console.log(date);

// 01 january, 1970 UTC + 100000000000milliseconds
date = new Date(100000000000);
console.log(date);
▶ Try it

3. new Date(dateString)

The third method of creating a date object is new Date(dateString). This method takes a string argument and returns a Date object representing the date and time specified by the string.

Example

// Creating date object from date string
var date = new Date("05 05, 1996 17:00:00");
console.log(date);

// another string format
date = new Date("November 11, 1997 01:00:00");
console.log(date);
▶ Try it

4. new Date() With Parameters

The new Date(year, month, day, hours, minutes, seconds, milliseconds) accepts 7 parameters. This return standard date is based on passed arguments.

All the parameters should have the same sequence as mentioned, where year and month are compulsory and the rest are optional.

Let's look at all the 7 parameters:

Let's look at all possible combinations of parameters:

Example

// using all parameters
var date = new Date(2010, 6, 21, 9, 15, 55, 250);
console.log(date);

// leaving milliseconds
date = new Date(2010, 6, 21, 9, 15, 55);
console.log(date);

// leaving seconds
date = new Date(2010, 6, 21, 9, 15);
console.log(date);

// leaving minutes
date = new Date(2010, 6, 21, 9);
console.log(date);

// leaving hours
date = new Date(2010, 6, 21);
console.log(date);

// only year and month
date = new Date(2010, 6);
console.log(date);

// if you think of removing month too
// then year will be treated as milliseconds
// remember this => new Date(milliseconds)
▶ Try it

Javascript Date Methods

The Date object has several methods that can be used to get information about the date and time.

Here is the list of most important methods:

Method Description
getFullYear() Returns the four-digit year for the specified date according to local time.
getMonth() Returns the month (from 0 to 11) for the given date according to local time.
getDate() Returns the day of the month (from 1 to 31) for the specified date according to local time.
getDay() Returns the day of the week (from 0 to 6) for the given date according to local time.
getHours() Returns the hour (from 0 to 23) for the specified date according to local time.
getMinutes() Returns the minutes (from 0 to 59) for the given date according to local time.
getSeconds() Returns the seconds (from 0 to 59) for the specified date according to local time.
getMilliseconds() Returns the milliseconds (from 0 to 999) for the given date according to local time.
getTime() Returns the number of milliseconds since midnight January 1, 1970, for the specified date according to local time.

1. getFullYear() Method

If you want to get the current year, you can use getFullYear() method.

The getFullYear method returns the full year of the date in local time.

Possible mistake: Use getFullYear() not getYear().

Example

var today = new Date();

// full year of the date in local time
var year = today.getFullYear();
console.log(year);
▶ Try it

2. getMonth Method

The getMonth() method returns the current month of the date as a number between 0 to 11 in local time.

Month return is 0 based, so January is 0, February is 1, and so on.

Example

var today = new Date();

// current month of the date in local time
var month = today.getMonth();
console.log(month);

// list of months
var months = [
  "January", "February", "March",
  "April", "May", "June", "July",
  "August", "September", "October",
  "November", "December"
];
console.log(months[month]);
▶ Try it

3. getDate Method

The getDate() method returns the day of the month in numbers from 1 to 31 in local time.

It represents the date of the month.

Example

var today = new Date();

// today's date
var date = today.getDate();
console.log(date);
▶ Try it

4. getDay Method

The getDay() method returns the day of the week for the specified date as a number between 0 and 6 in local time.

You can create an array of days of the week and use it to get the name of the day.

Example

var today = new Date();

// today's day
var day = today.getDay();
console.log(day);
  
// list of days
var days = [
  "Sunday", "Monday", "Tuesday",
  "Wednesday", "Thursday", "Friday", "Saturday"
];
console.log(days[day]);
▶ Try it

5. getHours Method

getHours() method returns the current hour of the day in local time as a 24-hour clock.

It returns a number between 0 and 23 where 0 is midnight and 23 is 11 PM.

Example

var today = new Date();

// current hour from 0-23
var hour = today.getHours();
console.log(hour);
▶ Try it

6. getMinutes Method

getMinutes() method returns current minutes of the hour in local time as a number between 0 and 59.

Example

var today = new Date();

// current minute from 0-59
var minute = today.getMinutes();
console.log(minute);
▶ Try it

7. getSeconds Method

getSeconds() method returns current seconds of the minute in local time as a number between 0 and 59.

Example

var today = new Date();

// current second from 0-59
var second = today.getSeconds();
console.log(second);
▶ Try it

8. getMilliseconds Method

getMilliseconds() method returns current milliseconds of the second in local time as a number between 0 and 999.

Example

var today = new Date();

// current milliseconds from 0-999
var milliseconds = today.getMilliseconds();
console.log(milliseconds);
▶ Try it

9. getTime Method

getTime() method returns the number of milliseconds since midnight January 1, 1970.

This method always uses UTC for time representation. For a client browser in any time zone, it will always give the same result.

Example

var today = new Date();

  
// milliseconds since January 1, 1970
var totalTime = today.getTime();
console.log(totalTime);
▶ Try it

Digital Clock In Javascript

Let's use the Date object and almost all of the methods mentioned above to create a digital clock.

This digital clock will be updated every second and will show the current date and time.

We are also going to use the concept of the setInterval method to update the clock every second.

# HTML Code

digital clock

Here is the HTML code:

HTML Code

<div class="container">
  <div class="clock">
    <div class="date"></div>
    <div class="time">
      <div class="hours"></div>
      <div class="minutes"></div>
      <div class="seconds"></div>
    </div>
  </div>
</div>

The HTML code is very simple. We have a container that holds the clock. The clock has a date and time section. The time section has three divs that will hold the hours, minutes, and seconds.

Now let's create the JavaScript code.

# JavaScript Code

First, select all the elements using the querySelector method.

var clock = document.querySelector('.clock');
var date = clock.querySelector('.date');
var time = clock.querySelector('.time');
var hours = time.querySelector('.hours');
var minutes = time.querySelector('.minutes');
var seconds = time.querySelector('.seconds');

Now we need to create a function that will update the clock every second.

First, create a function called updateClock.

function updateClock() {
  var now = new Date();
  var hoursText = now.getHours();
  var minutesText = now.getMinutes();
  var secondsText = now.getSeconds();

  if (hoursText < 10) {
    hoursText = '0' + hoursText;
  }

  if (minutesText < 10) {
    minutesText = '0' + minutesText;
  }

  if (secondsText < 10) {
    secondsText = '0' + secondsText;
  }

  hours.innerHTML = hoursText + ':';
  minutes.innerHTML = minutesText + ':';
  seconds.innerHTML = secondsText;
}

In this function, we create a new Date object and get the current hour using the getHours method, minutes using the getMinutes method, and seconds using the getSeconds method.

Then we add a zero to the hours, minutes, and seconds if they are less than 10.

Then set the innerHTML of the hours, minutes, and seconds to the current hour, minutes, and seconds.

Now create a function called updateDate.

function updateDate() {
  var now = new Date();
  var day = now.getDate();
  var month = now.getMonth() + 1;
  var year = now.getFullYear();

  if (day < 10) {
    day = '0' + day;
  }

  var ordinals = day === '01' ? 'st' : day === '02' ? 'nd' : day === '03' ? 'rd' : 'th';

  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

  date.innerHTML = day + ordinals + ' ' + months[month - 1] + ', ' + year;
}

In this function, we create a new Date object and get the current day using the getDate method, month using the getMonth method, and year using the getFullYear method.

Then we add a zero to the day if it is less than 10.

Now set ordinals and convert months to words using the indexOf method.

Finally set the innerHTML of the date to the current day, month and year.

In the last step call both the function every second using the setInterval method.

# Complete code

Complete Code

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Digital Clock</title>

  <style>
    body {
      margin: 0;
    }

    .container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background-color: #e98e8e;
    }

    .clock {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 250px;
      height: 250px;
      background-color: rgb(250, 234, 143);
      border-radius: 50%;
      box-shadow: 0 0 10px #ddd;
    }

    .date {
      font-size: 1.5em;
      font-weight: bold;
      color: #333;
    }

    .time {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 3em;
      font-weight: bold;
      color: #333;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="clock">
      <div class="date"></div>
      <div class="time">
        <div class="hours"></div>
        <div class="minutes"></div>
        <div class="seconds"></div>
      </div>
    </div>
  </div>

  <script>
    var clock = document.querySelector('.clock');
    var date = clock.querySelector('.date');
    var time = clock.querySelector('.time');
    var hours = time.querySelector('.hours');
    var minutes = time.querySelector('.minutes');
    var seconds = time.querySelector('.seconds');

    function updateClock() {
      var now = new Date();
      var hoursText = now.getHours();
      var minutesText = now.getMinutes();
      var secondsText = now.getSeconds();

      if (hoursText < 10) {
        hoursText = '0' + hoursText;
      }

      if (minutesText < 10) {
        minutesText = '0' + minutesText;
      }

      if (secondsText < 10) {
        secondsText = '0' + secondsText;
      }

      hours.innerHTML = hoursText + ':';
      minutes.innerHTML = minutesText + ':';
      seconds.innerHTML = secondsText;
    }

    function updateDate() {
      var now = new Date();
      var day = now.getDate();
      var month = now.getMonth() + 1;
      var year = now.getFullYear();

      if (day < 10) {
        day = '0' + day;
      }

      var ordinals = day === '01' ? 'st' : day === '02' ? 'nd' : day === '03' ? 'rd' : 'th';

      var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

      date.innerHTML = day + ordinals + ' ' + months[month - 1] + ', ' + year;
    }

    updateClock();
    updateDate();

    setInterval(updateClock, 1000);
    setInterval(updateDate, 1000);
  </script>
</body>

</html>
▶ Try it

Javascript Format Date

The date and time provided by the new Date() method are not formatted in standard formats that we use in our daily lives. We need to format the date and time in a standard format.

Example of few formats are as follows:

The following code snippet shows how to format the date and time in the above formats.

Example

function formatDate(date, separator) {
  var day = date.getDate();
  var month = date.getMonth() + 1;
  var year = date.getFullYear();

  if (day < 10) {
    day = '0' + day;
  }
  if (month < 10) {
    month = '0' + month;
  }

  return day + separator + month + separator + year;
}

var now = new Date();
console.log(formatDate(now, '/'));
console.log(formatDate(now, '-'));
console.log(formatDate(now, '.'));
▶ Try it

Another way to format the date and time is to use the toLocaleDateString() method of the Date object.

It accepts locales and options as parameters. The locales can be 'en-US', 'en-GB', 'en-IN', 'hi-IN', etc and options are way to format the date and time like { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }.

The toLocaleDateString() method returns a string with the date formatted according to the current locale.

Example

var now = new Date();
            
// Format the date and time in the default format
console.log(now.toLocaleDateString());

// Format the date with the given locale and options
let options = { year: 'numeric', month: 'long', day: 'numeric'};
console.log(now.toLocaleDateString('en-US', options));
console.log(now.toLocaleDateString('hi-IN', options));
▶ Try it

Conclusion

The Date object creates in 4 different ways gives us access to both local and UTC time. It provides multiple methods to get different aspects of the date and time like day, month, year, hours, minutes, seconds, milliseconds, timezone offset, etc.

The Date object also provides methods to format the date and time in different formats.