JavaScript Date Object: The Beginner’s Guide to JavaScript Date and Time

Date and time values are used for many important functions such as searching, validation, and report generation. There is no standard format for dates in web applications, as people in different time zones and countries prefer different formats. Therefore, adapting to any kind of date format can be a challenge as a front end developer. Today, we are going to see how to effectively use date and time functions in JavaScript.

Getting Started with the Date Object

The basic Date constructor takes no parameters, and is initialized to the current date, as shown below. We can clearly see that the resulting date depends on your local time zone, as two different time zones are shown.

<script>
  var today = new Date();
  // Thu Feb 27 2013 15:15:25 GMT+1000 (EST)
  // Thu Feb 27 2013 10:45:25 GMT+0530 (IST)
</script>

There are two primary ways of using the Date object:

  • Custom dates can be generated by providing the format or specific date as the parameter to the Date constructor.
    <script>
      date1 = new Date ( "January 6, 2013" );
    </script>
    
  • Then we can work with the created dates using dozens of built in functions. The following code shows you how to extract each component of a date using available functions.
    <script>
      date1 = new Date ( "January 6, 2013" );
      date = date1.getDate();
      year = date1.getFullYear();
      month = date1.getMonth();
    </script>
    

Let’s discuss some of the basic things you should be aware of when using date functions. Generally, we will be using the date, month, and year components. Dates can be between 1 and 31, and months can range from 0 to 11. The following code creates a Date object, and sets the day of the month to the 20th.

<script>
  date1 = new Date ();
  date1.setDate(20);
</script>

Also you are allowed to use numbers which don’t fall into the above ranges, to generate future or past dates. Consider the following example which uses values beyond the specified ranges.

<script>
  date1 = new Date ();
  date1.setDate(-1);
  date1.setMonth(-1);
</script>

Assume that current date is February 20th, 2013. The above code will change to the second to last date of the previous month in the previous year, which would be December 30th, 2012. Similarly, you can use values greater than 31 for date and 11 for month to generate future dates. Having learned how to use Date object to generate dates using various methods, let’s see how we can format dates.

Date Formatting

There is no single common format for dates, and we need to show date strings in different formats according to different situations. Basically, it is a two way process where we have to convert the string into a Date object first and then convert it back to a string in the format we prefer. The initial process consists of converting the string provided by user input into a Date object. Let’s consider some of the common user input methods for dates.

In the past, we had plain text fields or three option fields to select the month, day, and year. Nowadays, user input elements has been improved dramatically, and date pickers have become the modern way of selecting dates. Apart from date pickers, JavaScript calendars are a widely used component which we have to consider in this initial process. Dates from these components are retrieved as strings. If the date string contains a common format, we can just create the Date object by passing the input field value as shown below.

<script>
  // Assume date is 2013-02-15
  var current = $("start_date").value();
  var date1=new Date(current);
</script>

If you are working with calendars, the date will be specified as a HTML5 data attribute instead of the value property. An example of this is shown below.

<div id="start_date" class="date" date-current="2013-02-15"></div>
<script>
  var current = $("start_date").attr("date-current");
  var date1=new Date(current);
</script>

Most date pickers and calendars provides a wide range of predefined formats you can use. But, if the component does not provide a common format, or the date is specified as a code, then we have to construct the Date object manually by using functions as shown below.

<script>
  var month = {"JAN":"01","FEB":"02"};
  var current = "2013-FEB-22";
  var date_components = current.split("-");
  var current_year = date_components[0];
  var current_month= month[date_components[1].toString()];
  var current_day = date_components[2];

  current = current_year+"-"+current_month+"-"+current_day;
  var date11=new Date(current);
  document.write(date1);
</script>

Since we know the meaning of each component, its possible to split the date string, and construct a common format to parse the Date object.

Now we have converted the date string provided by user into a JavaScript Date object to handle the validations, comparisons, and whatever else is required by the application. Finally, we have to convert it back a string to save it or display it in the web browser. This conversion is much easier than the previous one since we can use functions to break the components. I think you should have a common conversion function to reuse across all the projects. Let’s develop a simple function to convert dates into various string formats.

<script>
  var date=new Date();
  var format = "YYYY-MMM-DD DDD";
  document.write(dateConvert(date,format));

  function dateConvert(dateobj,format){
    var year = dateobj.getFullYear();
    var month= ("0" + (dateobj.getMonth()+1)).slice(-2);
    var date = ("0" + dateobj.getDate()).slice(-2);
    var hours = ("0" + dateobj.getHours()).slice(-2);
    var minutes = ("0" + dateobj.getMinutes()).slice(-2);
    var seconds = ("0" + dateobj.getSeconds()).slice(-2);
    var day = dateobj.getDay();
    var months = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
    var dates = ["SUN","MON","TUE","WED","THU","FRI","SAT"];
    var converted_date = "";

    switch(format){
      case "YYYY-MM-DD":
        converted_date = year + "-" + month + "-" + date;
        break;
      case "YYYY-MMM-DD DDD":
        converted_date = year + "-" + months[parseInt(month)-1] + "-" + date + " " + dates[parseInt(day)];
        break;
    }

    return converted_date;
  }
</script>

Here, we have a function which takes a Date object and desired format as parameters. Inside the function, all the date components are assigned into variables using functions. Then, we have a switch statement to choose the format. This kind of reusable utility function can be very effective for developing applications. When you are asked to provide a new format, just add another entry to the switch statement, and return the components according to the new format. The output of the code will be 2013-FEB-17 SUN. Likewise, you can convert it into your own preferred formats for displaying.

Date Comparisons

Searching records between a given date range is one of the most common use of dates in web applications. First, we have to convert the date string provided by user into a Date object before thinking about comparisons. Let’s compare two dates generated with different methods, as shown below. It’s wise to use the getTime() method to compare dates. Assume these dates were both generated on February 18th, 2013.

<script>
  var date1=new Date();
  var date2=new Date("2013-02-18");

  if(date1.getTime() == date2.getTime()){
    console.log("Dates are equal");
  }
</script>

Even though both objects contain the same date, they are not equal. date1 contains the current date and will include the current time. But, date2 will not contain the current time, and hence it will not match.

The solution is to set the time of both objects to a standard time format. I have seen a lot of developers set the time to 00:00:00 for the current date object, as shown below.

<script>
  var date1=new Date();
  date1.setHours(0,0,0,0);
  var date2=new Date("2013-02-18");
</script>

So, date1 will be something like Mon Feb 18 2013 00:00:00 GMT+0530 (IST). But, it still doesn’t match since date2 will contain the time in your local time zone, which is GMT+5.30 for me. If you don’t want to consider the time, the best way is to set both dates into the same time, as shown below.

<script>
  var date1=new Date();
  date1.setHours(0,0,0,0);
  var date2=new Date("2013-02-17");
  date2.setHours(0,0,0,0);
</script>

We can use same technique for comparing date ranges as well. Make sure to set all the other components of both dates to the same value and only check for the components which vary across both dates.

Should We Use a Date Manipulation Library?

Throughout the article we discussed how the Date object works, and necessary functions we can use to manipulate dates. Choosing a date manipulation library is something you have to decide based on your requirements. Simple date handling can be done easily without a library. But, if you want complex functionality, I suggest you to use a date manipulation library like Datejs, which provides the ability to implement complex features through nested function calling.

And if you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like Jump Start JavaScript.

Comments on this article are closed. Have a question about TOPIC? Why not ask it on our forums?

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Yin

    Correction for example:

    “Assume that current date is February 20th, 2013. The above code will change to the second to last date of the previous month in the previous year, which would be January 30th, 2012.”

    It should be December 30th, 2012.

    • http://www.innovativephp.com Rakhitha Nimesh

      Hi Yin

      Thanks for pointing out the mistake on date. It has been fixed now.

  • http://www.brothercake.com/ James Edwards

    Actually there is a standard format for dates in web applications — that format is ISO 8601, which is what the “datetime” input produces. There’s usually no need to work with dates in any other format, although for visual output you’d probably want something more friendly.

    The best way to compare dates and times is to work with them as UTC, and the Date object includes UTC versions of all its functions, eg getUTCDate() rather than getDate()

    Several of your examples show dates being passed to the Date constructor without a time component, e.g. new Date(“2013-02-17″), however this is bad practise. When you pass a date to the constructor it should always include the time, otherwise the result will be ambiguous or fail entirely — Firefox will assume that it’s midnight UTC, Opera will assume that it’s midnight local time, and Safari won’t parse it at all. Also, IE8 and earlier don’t support that format as the input to Date at all, so it’s usually better to construct dates using a unix timestamp, or by passing no input an at all and then setting the individual components using the setFoo functions.

    • http://www.innovativephp.com Rakhitha Nimesh

      Hello James

      Sorry for being late to reply.

      Thank you very much for the detailed suggestions. It’s always good to have the feedback from experienced developers in this subject.

      Thanks for mentioning about ISO 8601 format. What I focused on was the visual output and the necessary formats when working with jQuery date pickers and calendars.

      Its good to know that getUTCDate is better than getDate in comparing dates.

      I missed the details on how different browsers define the time. Thanks for mentioning the importance. So should we pass 00:00:00 when defining dates?

      • http://www.brothercake.com/ James Edwards

        Yes, exactly so — if the time is not important to the output, then specify midnight.

  • http://poetro.hu/ Peter Galiba

    Please don’t use parseInt without a radix. Lets say, the currently the month is “08″ or “09″. Then the parseInt(month) will return 0, which is of course not the expected month. Use parseFloat, if you don’t want to specify a radix, or specify it. Same goes for the day too.

    • http://www.innovativephp.com Rakhitha Nimesh

      Hello Peter

      Thanks for pointing out the mistakes in the codes.

      I’ll try to update the article with correct codes as soon as I can.

  • http://www.ama3.com/anytime/ Andrew

    The Any+Time™ library includes an extremely simple and powerful date/time parse/format utility called AnyTime.Converter, which can convert a Date object to a string of practically any format, and vice-versa. Use is free under the CC BY/NC/SA license, which includes commercial sites under most circumstances. It also includes the most powerful, flexible and easy-to-use picker on the planet! For more information, visit ama3.com/anytime .

    • http://www.innovativephp.com Rakhitha Nimesh

      Hello Andrew

      Thanks for the comment.

      I’ll definitely look at Any+Time library.

  • Pingback: Newsletter 1 – October Sky Studios