This blog post is meant for ASP.NET website and web application beginners who are striving their way through learning processes and want to build their own ASP.NET websites or web applications which makes use of real-time processes and/or some basic stuff like user profiles where they would be using some code to display the age of the user of whom profile is being viewed. I will be giving an overview of the
DateTime object that would be used in ASP.NET website (so please make up your mind, that I am not actually talking about the
DateTime object itself, instead I am going to talk about the procedures that will be taken in order to create a better user-interface for your website, so you can categorize this blog post as a front-end developer only post. If you’re interested in learning about the
DateTime object, or wanted to learn about it and were redirected to this web page, then you’ll be wasting your time reading any further, please go to this article of mine that explains the
DateTime object in .NET framework) and how you can use different methods and server-side codes (I will be using C#, you can choose your own) to use the objects to provide the data for your users and to build the user-interface that makes use of date instances, like age calculator, calender applications, etc.
What Might Be the Use of DateTime Object?
Since ASP.NET developers are unaware of the actual processes taking place in the back end, because of awesome-ness of the ASP.NET framework, usually the new developers are left in the dark of what actually these objects and functions are. The major thing and the major problem in this process is the usage of the keyword “
var” in the ASP.NET web applications. Although it leaves a lot of not-required code behind (as in the second code line) but still it doesn't allow new developers to understand the concept of “variable declaration“.
var dateTime = DateTime.Now;
DateTime dateTime = DateTime.Now;
I had the same problem in the beginning. I didn’t know that each object must be saved in its own data type, and that is why I was unable to solve a problem where it said, “Unable to convert type right-value to left-value.” and that is why I thought it must be noted here, that no wonder ASP.NET is being used as a framework for web applications and there is a lot of abstraction in .NET framework and the ASP.NET, ASP.NET provides different assemblies as compared to those provided in the .NET framework and thus it usually feels like the code just runs.
DateTime object is used to represent different elements in HTML which require some data that would be better represented by the
DateTime object, like a calender application, although you can write a loop for 31 days, but who wants to when you’ve got a structure to take care of that for you?
DateTime is a struct in .NET, it is not a class. See MSDN for more specification. There is a difference between them both, one is value-type and other is reference-type; class is reference-type.
Similarly, you can perform different other tasks using
DateTime object, such as finding the age and all other such processes. I will be explaining the concepts of finding the age, and the code required to complete the process in this blog post later. Until then, it is just a few scenarios that you might want to accomplish using
DateTime object. Sometimes, your user wants to edit the way he gets to see the date on your application, the default machine date would be displayed as month/day/year, but people here from Pakistan are more familiar with day/month/year, you would have to either define multiple modules for that. Or, you can easily just use the
DateTime object and display the dates in different formats that the user wants.
I would show how to pass simple string-like formats to the objects, to create their string notations. This would help you in different scenarios, such as fetching the user-friendly formats from database or other data source, etc.
Using the DateTime in ASP.NET Applications
Although ASP.NET applications are now using the .cshtml (or for VB.NET developers .vbhtml) pages which come embedded with all of the required assemblies already included into the file, for you to simply use them without having to reference them all one-by-one such as System and a bunch of other ASP.NET-required assemblies, but still you can make use of the .NET assemblies by using them as you would do them in any C# application.
DateTime is found in the
System namespace, so no further reference is required. You can use the
DateTime object directly in the web page. Let us create our first module.
Calculating the Age of the User
Of course for the user’s age, we’re going to use a
DateTime object, to get the year and then the month and date of the user. I can’t say about the old days, but yes, you can possibly do that using three different integer values too; one for year, month and day. But since you have got the
DateTime object, you can easily just use this object and let the .NET framework handle the rest of the things for you.
A user’s age is the total days (in .NET framework I am talking, because there are no Years in .NET, just Day member) the member has lived on the planet, that started from the day he got born, or you can add some extra precision to the instance, by adding the hours, minutes and seconds for when the person was born. To calculate the age, you would subtract that date (birthdate) from the very now instance. In .NET framework, you can get the current instance of the time by using
DateTime. Now, it is a
static member, so you can get this value without having to create a new instance. Now let us write the code to calculate the age of the user. Suppose, I was a user, I would do it this way.
Did you know: A year is made up of 365.25 days, that is why there is a leap year after every 4 years.
var dateOfBirth = new DateTime(1995, 2, 2);
var timeSpan = DateTime.Today.Subtract(dateOfBirth);
var age = (int) (timeSpan.TotalDays / 365.25);
This above code would find the age for the user (note the 356.25 in the division operator, if you would use the 365, then the age would be a little more than the real one). For me, it gave me 19; well that is my age at this instance of time, I might be elder when you are reading this blog post.
Age calculator. Provides the age of the user by using a DateTime object.
I do not need to show the HTML code, that was used, everyone knows this basic code to render the data in the HTML form.
Finding the Total Time Spent
Usually, there are some scenarios in which developers want to find a time span which has passed for some other instance of time. Like, how much time has elapsed since the last meeting, or how much time has passed since the last presentation, etc. In such conditions, .NET framework has introduced an object TimeSpan, which is used to display the actual time span between two
datetime objects. We all know the difference between two objects is found by subtracting the later one from the first one, the result in the case of
DateTime objects is a
Let us take another example of this case, we will take a date (no longer than a day) to test the hours, and another date (no longer than a year) to test the days that have been passed since that particular date.
var preTimeHour = new DateTime(2015, 2, 10);
var preTimeYear = new DateTime(2014, 8, 29);
var elapsedHours = DateTime.Now.Subtract(preTimeHour).Hours;
var elapsedYear = DateTime.Now.Subtract(preTimeYear).Days;
The above code would find the values that we’ve appened (.Hours, and .Days). The following output was printed in this case (in my instance of time; yours would not resemble).
These dates and their results depend on my machine’s time, the results on your screen would be different.
Another Similar Scenario
There is another similar scenario, like we see on different social platforms that the time of the social activity is shown, in a format like “<variable> minutes ago”. That is the similar thing above discussed, but a slight difference. That is, that in this case now seconds would be involved, to set the precision for the actual time that the activity took place.
Tip: Do not use the Seconds member of the TimeSpan in this case, use the TotalSeconds. TotalSeconds would return the total number of the seconds for the time span, Seconds would only return the seconds part of the current TimeSpan notation (0-59 only).
Let us take a few examples into consideration and see how .NET framework would let us know of how much time has been consumed since that time instance.
var list = new List<DateTime>();
list.Add(new DateTime(2014, 2, 2));
list.Add(new DateTime(2015, 1, 19));
list.Add(new DateTime(2015, 2, 12));
list.Add(new DateTime(2015, 2, 12, 1, 0, 0));
list.Add(new DateTime(2015, 2, 12, 0, 0, 0));
Now let us see, what did .NET render on the screen in the browser by using these instances. In the HTML markup, I wrote another code, to find the difference of the seconds. I am going to share that HTML markup (in Razor syntax) that you would be interested in reading in. Give the following markup a look:
@foreach (var dateTime in list)
// For each of the instance of the DateTime, check how much time has elapsed
var seconds = (DateTime.Now - dateTime).TotalSeconds;
The time that has elapsed since @dateTime.ToString("MMMM dd, yyyy hh:mm:ss") is
@if (seconds < 1)
// Zero seconds, hopefully that DateTime.Now object
@:zero seconds, thus <i>just now</i>.
else if (seconds > 0 && seconds < 60)
// Seconds are greater than zero but less than 61 (minute)
else if (seconds > 60 && seconds < 3600)
// seconds are greater than minute but less than hour
@:@(Convert.ToInt16(seconds / 60)) minutes.
else if (seconds > 3600 && seconds < 86400)
@:@(Convert.ToInt16(seconds / 3600)) hours.
@:more than a day.
Now the above code block would find the actual time that has elapsed. The only reason that it is a long one is that it had to perform some complex function, to find the actual instance, starting from a second, to minute, to hour and all the way to day. You can add more statements and conditions to test for a month, week or a year and so on. I am not going to create that entire solution plugin here, because it is just meant for a tutorial. The result of the above code was something like this:
Time Span representation of the date.
Different Formats of DateTime Object
In our applications, we need to display the
DateTime object in the format that user loves to view. Think of it like a user from America would be interested in reading the date in the format month/date/year, but a user from Pakistan would be loving to read the date in the format date/month/year. Now, .NET framework allows you to format your date into the format that you love it in. That is why, the
.ToString() function of the
DateTime object is overridden and overloaded to allow you to pass multiple values and parameters to change the format of the date in the format that the user wants.
Tip: Using the method I am going to show, you can use a string value from the database and pass it to the .ToString() function of the object and it would show it in that format.
I created a few
string formats for date. That I would be using to display our date in, I am going to use a single instance of the
DateTime, to remove any ambiguity from your minds and to show it in different formats by using those formats.
var formats = new List<string>();
formats.Add("MMMM dd, yyyy");
formats.Add("MMMM dd, yyyy hh:mm");
formats.Add("MMMM dd, yyyy 'at' hh:mm ss");
formats.Add("MMMM dd, yy hh:mm");
formats.Add("MMMM dd, yy dddd");
Now, the result of this
string elements list would be printed, they would be used as format for the
DateTime object, for the
string notation of it. I used the following HTML, to convert the date into the representative
@foreach (var format in formats)
@:"@format" is used to render the DateTime object as, <b>@DateTime.Now.ToString(format)</b>.
The result of this (at my instance of time was):
DateTime object different formats.
This is the blog post of mine to explain the concept of the
DateTime object in ASP.NET website.
Points of Interest
DateTime object is available in the .NET framework, and can be used in the ASP.NET website. If you use .cshtml, then you can make a good use of these assemblies without having to reference them in your file, they’re already there for you.
You can use the
DateTime object in performing different functions in the ASP.NET websites, that require to use a date-like data, such as calender applications.
DateTime is an effective way of completing your project, instead of using integer data values for month, date and year, etc.
You can pass simple
string-data formats for the
DateTime notation to convert the
DateTime object into your own custom string notation. For more on this, you can read this MSDN document.