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.





var today = new Date ( ) ;

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. date1 = new Date ( "January 6, 2013" ) ;

constructor. 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. date1 = new Date ( "January 6, 2013" ) ; date = date1 . getDate ( ) ; year = date1 . getFullYear ( ) ; month = date1 . getMonth ( ) ;

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.

date1 = new Date ( ) ; date1 . setDate ( 20 ) ;

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.

date1 = new Date ( ) ; date1 . setDate ( - 1 ) ; date1 . setMonth ( - 1 ) ;

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.

var current = $ ( "start_date" ) . value ( ) ; var date1 = new Date ( current ) ;

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.

var current = $ ( "start_date" ) . attr ( "date-current" ) ; var date1 = new Date ( current ) ;

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.

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 ) ;

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.

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 ; }

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.

var date1 = new Date ( ) ; var date2 = new Date ( "2013-02-18" ) ; if ( date1 . getTime ( ) == date2 . getTime ( ) ) { console . log ( "Dates are equal" ) ; }

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.

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

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.

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

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?