Date formatting in JavaScript

In previous chapter, JavaScript date object, we explained how to work with the date objects in JavaScript. In your web projects, you generally need to format date according to the requirements.

For example, showing date in “dd/mm/yyyy” or “mm/dd/yyyy” or localized format, showing day name of the Week with the Month name and year etc.

This chapter will show you examples of how you can use date object to format date. Generally, date methods provided by JavaScript returns integer numbers as shown in the examples below.

JavaScript getDay and getMonth methods example

The following example returns day number of the Week and Month number by using getDay and getMonth methods.

Experience this example online

As you can see, the day and month number are shown in an alert by using the date methods. The getDay returns day number of the Week starting from 0 for Sunday and 6 for Saturday. Whereas getMonth returns month number, 0 for Jan and 11 for Dec.

You may wonder why it starts from 0 rather 1 for Sunday and same happens for Month number. The reason is, as date functions in JavaScript return numeric values you may have to use arrays to format the date. As array index starts from 0, this will reduce coding effort.

The date formatting can be done by using external libraries like date js. The sugar.js also has extensions to the date object. In this tutorial, we will show format date by using arrays in our examples.

The date format in dd-Month–YYYY example

Following is an example of JavaScript format date. It will show local date in the “dd-Month-YYYY” format by using date object. Click the link below to see the example online:

Experience this example online

In the demo, the month names are stored in a Month_name array. Then we used a variable, current_month, to get current month’s integer value that acted as an index for array while showing short Month name in date format example.

The formatted date with Weekday name format

The following example shows Weekday name along with day, month and year. The date formatting will be as follows:

Experience this example online

As you can see the date is shown in e.g. “Fri, 1 June 2012″ format.

Similarly, you can format date according to local format like mm/dd/yyyy by using concatenating characters.

JavaScript date format in dd/mm/yyyy and mm/dd/yyyy example

Following is an example of JS date format in the “dd/mm/yyyy” and “mm/dd/yyyy” format. Two buttons are shown, one for each format. As you click on the button, the local date in specified format will be shown in an alert.

Experience this example online

You can see the formatted date is shown in the alerts.

As mentioned earlier you can also include external date libraries as well to work with date formatting.