Formatting Date and Calculating Age in JavaScript

Introduction

If you are a web developer, you would know that formatting a date in server-side language is not a very much tough task at hand, all you need is a basic understanding of the language, what logic you need and there, you have the well formatted date time object. For example, the following C# code is a very formatted code that can provide you with a formatted date time object, in a way that you want it to be.
  1. var dateOfBirth = new DateTime(1995, 08, 29); // My date of birth  
  2. var formatted = dateOfBirth.ToString("MMMM dd, yyyy");  
  3. // Would hold: August 29, 1995  
In the above code, I have provided the format that I want the date to be in and the code would provide me with the result that I am expecting. However, doing so in JavaScript takes a lot of pain, there is no overridden ToString function in JavaScript that you can provide with date object to get a properly formatted date value.

JavaScript date object however does provide functions that you can use to get the month, date or year values. I would use those functions to generate the formatted string for the date object. Also note that in JavaScript, a date object is just the number of milliseconds that have passed since 1st January 1970 00:00:00 AM.  That is why, do not try to write your own code to calculate the months and dates, instead use the built-in functions of getMonth, getDate etc to get the values. Read the article for more on this, I will show you how to write the code and also how to properly format the string notation of date object. At the end I will provide an age calculator as a bonus code sample!

JavaScript Date object

JavaScript date object is pretty much compact edition of date objects provided in other languages and frameworks. It doesn't provide many functions and features instead just a constructor that takes number of milliseconds or string that represents a date time object ranging from 1 January 1970 to Today (whatever today is). You can create an instance easily, just use the following code, 
  1. var date = Date.now(); // current date time  
  2.   
  3. // OR  
  4.   
  5. var date = new Date(); // new instance; default  
  6.   
  7. // OR  
  8.   
  9. var date  = new Date('string-notation-of-datetime');  
  10. // Any date time upto 1 January 1970 from Now.  
Now, let us work around with the source code that we have currently and see what can JavaScript offer us.

Writing the web application

In your HTML, you can define input fields that values from users and setting their type to any one from a range would allow the users to enter a value type from any one of those types. In our article, we will use date type. I have used the following HTML markup, 

Note: I have used Bootstrap for style. 
  1. <input type="date" class="form-control" />  
After rendering the control,
 
HTML rendered in Chrome Browser.

Ok that is what we have for the layout, now let us handle the input that user provides us with. We have to find the string that represents the date time provided by user, also we have to find the age of user. So, let us write the JavaScript code. I will comment the code to explain it step by step for you. 
  1. var dateValue = new Date($('input').val()); // Get the value  
  2.   
  3. // Now comes the stringification... Following code does that.  
  4. var date = getMonth(dateValue.getMonth()) + " " + dateValue.getDate() + ", " + dateValue.getFullYear();  
In JavaScript, the getDate, getMonth methods return Number objects. So, instead of using that number in the date. I created another function that gets the month for my integer value.

Note: date.getMonth() returns zero based number. 
  1. function getMonth(index) { // Pass the index as parameter  
  2.     switch (index) { // Switch on index  
  3.         case 0:  
  4.             return "January";  
  5.             break;  
  6.         case 1:  
  7.             return "February";  
  8.             break;  
  9.         case 2:  
  10.             return "March";  
  11.             break;  
  12.         case 3:  
  13.             return "April";  
  14.             break;  
  15.         case 4:  
  16.             return "May";  
  17.             break;  
  18.         case 5:  
  19.             return "June";  
  20.             break;  
  21.         case 6:  
  22.             return "July";  
  23.             break;  
  24.         case 7:  
  25.             return "August";  
  26.             break;  
  27.         case 8:  
  28.             return "September";  
  29.             break;  
  30.         case 9:  
  31.             return "October";  
  32.             break;  
  33.         case 10:  
  34.             return "November";  
  35.             break;  
  36.         case 11:  
  37.             return "December";  
  38.             break;  
  39.         default// Wouldn't get called usually because range is 0-11  
  40.             "Invalid number: " + index;  
  41.             break;  
  42.     }  
  43. }  
The above function once called returns the string for the month. That is why, our code above would be able to get the date in a string representation. Now continuing to the age function, calculating the age is not as simple as in C# or other languages. You have to manually negate the value of 1970 from the date object of milliseconds resulted from the subtraction of date of birth from current time. Confused? So am I, let us check out the code it would simplify the statement. 
  1. var age = Math.abs(  
  2.               new Date(  
  3.                    Date.now() - dateValue // 1. Get the difference as new Date object  
  4.               ).getUTCFullYear() - 1970 // 2. Calculate the years  
  5.           ); // 3. Get the value  
I have separated the process in three stages. 
  1. First of all, you get the value after negating the date of birth from current date. This would be the basic building block for our age algorithm. 

  2. Get the UTC year value for the value returned by the negation, subtract 1970 from it. 

  3. Now, get the absolution value of what was returned from Step 2
Now, this would hold the age value for your user's input. Running the above function and getting the HTML for my own age is like this, 
 
 
HTML markup showing date in formatted string and age of user.

Conclusion 

Now, you can see how to select user's input and calculate the age from it in JavaScript, and how to represent it in a string notation for easier reading for users. Feel free to use the code, and share it with other fellows also. 

Up Next
    Ebook Download
    View all
    Learn
    View all