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.
- var dateOfBirth = new DateTime(1995, 08, 29);
- var formatted = dateOfBirth.ToString("MMMM dd, yyyy");
-
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,
- var date = Date.now();
-
-
-
- var date = new Date();
-
-
-
- var date = new Date('string-notation-of-datetime');
-
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.
- <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.
- var dateValue = new Date($('input').val());
-
-
- 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.
- function getMonth(index) {
- switch (index) {
- case 0:
- return "January";
- break;
- case 1:
- return "February";
- break;
- case 2:
- return "March";
- break;
- case 3:
- return "April";
- break;
- case 4:
- return "May";
- break;
- case 5:
- return "June";
- break;
- case 6:
- return "July";
- break;
- case 7:
- return "August";
- break;
- case 8:
- return "September";
- break;
- case 9:
- return "October";
- break;
- case 10:
- return "November";
- break;
- case 11:
- return "December";
- break;
- default:
- "Invalid number: " + index;
- break;
- }
- }
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.
- var age = Math.abs(
- new Date(
- Date.now() - dateValue
- ).getUTCFullYear() - 1970
- );
I have separated the process in three stages.
- 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.
- Get the UTC year value for the value returned by the negation, subtract 1970 from it.
- 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.