JavaScript Date and Time – Implementation of JavaScript Date Methods

I was just scrolling down through a website in the morning and suddenly a good morning message popped-up. This put me in a dilemma for a few minutes and I wondered how come a website gets to know that its a morning or a night. I was curious if JavaScript could do that for me, and guess what? It can. JavaScript is fully capable of accessing and manipulating date and time as per my needs. Now, let’s understand how.

This tutorial explains all you need to know about JavaScript date and time. You can use the current date and time or you can select the time frame you want. The choice is all yours and JavaScript helps you to produce the desired output easily. We will discuss the Date object in this tutorial, along with the numerous methods associated with it.

You can’t move forward in this tutorial until you clear your concepts of JavaScript Numbers

JavaScript Dates

Stay updated with the latest technology trends while you're on the move - Join DataFlair's Telegram Channel

JavaScript Date and Time

One of the features of JavaScript that make it so popular is its ability to use (within the script or in the user’s browser) the local date and time. This is the output of the JavaScript Date object. A Date object contains a Number that represents milliseconds since the date 1 January 1970 UTC. The value in the object changes dynamically as the local date and time changes. You can create a Date object in various ways.

new Date();
new Date(value);
new Date(dateString);
new Date(year, monthIndex [, dayIndex [, hours [, minutes [, seconds [, milliseconds]]]]]);

If you declare a variable without the new keyword, it will return date as a string. The program below implements both these approaches.

Note: You cannot alter the syntax or the sequence of the Date parameters. JavaScript will either invalidate the format (last statement of the program) or you get a jumbled date.

date1 = new Date()
// Sat Jul 27 2019 10:02:29 GMT+0530 (India Standard Time)
date1 = Date()
// "Sat Jul 27 2019 10:02:36 GMT+0530 (India Standard Time)"
date2 = new Date('July 27, 2019 10:40:00')
// Sat Jul 27 2019 10:40:00 GMT+0530 (India Standard Time)
date3 = new Date('2019-07-27T10:40:00')
// Sat Jul 27 2019 10:40:00 GMT+0530 (India Standard Time)
date4 = new Date(1995, 11, 17, 3, 24, 0)
// Sun Dec 17 1995 03:24:00 GMT+0530 (India Standard Time)
date4 = new Date(1995, 11, 17)
// Sun Dec 17 1995 00:00:00 GMT+0530 (India Standard Time)
date1 = new Date("2019-07-27 T 10:40:00")
// Invalid Date

Output:

JavaScript Date and Time Output

Take a deep dive and explore everything about JavaScript Strings

Individual Date and Time Component Values

We saw numerous parameters associated with our Date object above. We understand many of them by name, but JavaScript doesn’t always understand all the date formats that we do. So it’s crucial that you learn to give the script the correct description of the date you want, with the syntax that JavaScript understands. Let’s go through them, so you don’t get confused with the parameter’s values. Don’t forget that missing fields are given the lowest possible value (1 for the day and 0 for the rest of the components).

ComponentDescription
year
It represents the year as an integer value. All the values, except 0 to 99 (these map to the year 1900 to 1999), are actual years.
monthIndex
It is an integer value representing the month, with 0 for January to 11 for December.
dayIndex
It is an integer value representing the day of the month, with 0 for Sunday to 6 for Saturday.
hours
It is an integer value representing the hour of the day, with the default as 0 (midnight).
minutes
This integer value represents the minute segment of time, with the default as 0 minutes past the hour.
seconds
This integer value represents the second segment of time. The default is 0 seconds past the minute.
milliseconds
This integer value depicts the millisecond segment of time. The default is 0 milliseconds past the second.

JavaScript Date Methods

The Date object has the following types of methods for accessing and manipulating date and time:

1. Getter

These methods retrieve the specified parameter from the Date object. JavaScript doesn’t always return the same format as you want, but you can use these methods to convert them into user-understandable date format. The following table lists all the major methods you need to be aware of to be able to access dates.

MethodDescription
getDate()
This method returns the day of the month (1-31) for the specified date as per the local time.
getDay()
It returns the day of the week (0-6, from Sunday to Saturday) for the specified date according to local time.
getMonth()
It returns the month (0-11, from January to December) in the specified date according to local time.
getFullYear()
It returns the year (as a 4-digit number) of the specified date according to local time.
getHours()
This method returns the hour (0-23) for the specific date as per the local time.
getMinutes()
This method returns the minutes (0-59) for the specified date according to local time.
getSeconds()
It returns the seconds (0-59) for the specified date as per the local time.
getMilliseconds()
This returns the milliseconds (0-999) in the specified date as per the local time.
getTime()
This method returns the numeric value of the specified date: the number of milliseconds since January 1, 1970, 00:00:00 UTC (negative for the time before that).
getTimezoneOffset()
It returns the time-zone offset in minutes for the current locale.

The all above methods work with the local time. If you want to use Coordinated Universal Time (UTC), prefer the methods listed below. These perform the same tasks like the ones we discussed above, but with UTC.

getUTCDate()getUTCDay()getUTCMonth()
getUTCFullYear()
getUTCHours()getUTCMinutes()getUTCSeconds()
getUTCMilliseconds()

Let’s use the local time and JavaScript Date methods to print the current date and time in the format on the browser window:

Current Date: Tuesday, April 25, 2017
Current Time: 04: 10 PM

Code:

<html>
  <body>
    <p id = "date">
    <p id = "time">

    <script>
      var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; //array of days
      var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] //array of months
      var date = new Date(); //creating Date object
      var currentDay = days[date.getDay()]; //determining day using the array and method 
      var currentMonth = months[date.getMonth()]; //determining month using the array and method
      var currentDate = date.getDate(); //current date
      var currentYear = date.getFullYear(); //current year
      document.getElementById('date').innerHTML = "Current Date: " + currentDay + ", " + currentMonth + " " + currentDate + ", " + currentYear + "</br";

      var hrs = date.getHours(), min = date.getMinutes(); //current time (hours and minutes)
      var suffix = 'AM';

      if(hrs >= 12){
        hrs -= 12;
        suffix = 'PM';
      }
      if(hrs < 10){
        hrs = "0" + hrs;
      }
      if(min < 10){
        min = "0" + min;
      }
      document.getElementById('time').innerHTML = "Current Time: " + hrs + ": " + min + " " + suffix + "</br";
    </script>

  </body>
</html>

Screenshot:

Getter Current Date - JavaScript Date and Time

Output:

Getter Current Date Output - JavaScript Date and Time

Don’t worry, this is not a monster code, it is very easy to implement. Just keep track of all the variables and only use related identifiers. You can use individual methods to retrieve individual elements in the Date object.

2. Setter

These JavaScript methods manipulate the different parameters of the Date object. They set a part of the date and lets us alter the specific values. The methods in the table below produce results as per the local time.

MethodDescription
setDate()
This Date method sets the day of the month for a specified date.
setMonth()
It sets the month for a specified date.
setFullYear()
This method sets the full year (as a 4-digit number) for a specified date.
setHours()
This JavaScript method sets the hours for a specified date.
setMinutes()
It sets the minutes for a specified date.
setSeconds()
It manually sets the seconds for a specified date.
setMilliseconds()
This method sets the milliseconds for a specified date.
setTime()
It sets the Date object to the time represented by the number of milliseconds since January 1, 1970, 00:00:00 UTC (negative numbers for times before that).

JavaScript methods to work with UTC are as follows:

setUTCDate()setUTCMonth()setUTCFullYear()setUTCHours()
setUTCMinutes()setUTCSeconds()
setUTCMilliseconds()

You can’t afford to miss the article on JavaScript Objects

3. Conversion Getter

These methods get the results we want after conversion. This means that they first convert the Date object to a String object and then return the value. The list of these methods is as follows:

MethodDescription
toDateString()
It returns a string, containing the “date” of the Date object in a human-readable format.
toTimeString()
It returns a string, containing the “time” of the Date object in a human-readable format.
toUTCString()
It returns a string, containing the Date using the UTC timezone.
valueOf()
This method returns the primitive value of the Date object.
toString()
This method returns a string representation of the specified Date object.

You can use these methods when you want to use the standard date and time formats that JavaScript uses. Just remember, you cannot alter the format of the value returned. Also, these methods return String objects rather than Date objects. So you need to be careful when and where you use these methods. Let’s run the following statements in the browser console:

date.toDateString()
// "Sat Jul 27 2019"
date.toTimeString()
// "12:12:06 GMT+0530 (India Standard Time)"
date.toUTCString()
// "Sat, 27 Jul 2019 06:42:06 GMT"
date.valueOf()
// 1564209726170
date.toString()
// "Sat Jul 27 2019 12:12:06 GMT+0530 (India Standard Time)"

Output:
conversion getter output

Wow! We got the same result as the above code with a single line. We didn’t get the same format, but I think this is cool, don’t you? Experiment with these methods, see what happens. Notice the difference between different methods and their outputs. These methods are very beneficial if you know how to use them in your program.

Summary

Here we conclude our tutorial on JavaScript Date and Time. Date and time in JavaScript are very fascinating to use. You can do almost anything you want with dates: accessing, manipulating, etc. It also isn’t that difficult. All you need to do is get a hang of all the methods we discussed in this tutorial. Clear all your concepts regarding this topic and you won’t face any problem with dates in the future.

Next, you must go through our next article on JavaScript Array

Hope you liked our article.

Share your feedback and queries through the comment section below.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.