Overview of DateTime in ASP.NET

This article is meant for ASP.NET website and web application beginners who are struggling their way through the learning processes and want to build their own ASP.NET websites or web applications that use 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 the profile is being viewed. I will be providing an overview of the DateTime object to be used in the ASP.NET website. (So please make up your mind, that I am not actually talking about the DateTime object itself, instead I will talk about the procedures that will be taken to create a better user-interface for your website, so you can categorize this article as a front-end developer only post. If you're interested in learning about the DateTime object, or want 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 the .NET framework) I will be showing how to use various 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, calendar applications and so on.

Uses of the DateTime object


Since ASP.NET developers are unaware of the actual processes taking place in the back end and because of the awesome-ness of the ASP.NET framework, usually the new developers are left in the dark of what these objects and functions actually 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 much 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“.

  1. var dateTime = DateTime.Now;  
  2.   
  3. // is same as  
  4.   
  5. 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 said here that no wonder ASP.NET is being used as a framework for web applications and there is much abstraction in the .NET framework and ASP.NET. ASP.NET provides various assemblies compared to those provided in the .NET framework and thus it usually feels like the code just runs.

In ASP.NET, the DateTime object is used to represent various elements in HTML that require some data that would be better represented by the DateTime object, like a calendar 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 a value-type and the other is a reference-type; class is reference-type.

Similarly, you can do various other tasks using a 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 article later. Until then, it is just a few scenarios that you might want to accomplish using a 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 need to either define multiple modules for that. Or, you can easily just use the DateTime object and display the dates in the various formats that the user wants.

I would show how to simple string-like formats to the objects, to create their string notations. This would help you in various scenarios, such as fetching the user-friendly formats from the database or other data source and so on.

Using the DateTime in ASP.NET applications

Although ASP.NET applications are now using the .cshtml (or for VB.NET developers .vbhtml) pages that 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, you still can use the .NET assemblies by using them as you would 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 integer values too; one for year, month and day. But since you have the DateTime object you can easily just use this object and let the .NET framework handle the other things for you.

A user's age is the total days (in the .NET Framework I am talking about, because there are no years in .NET, just a 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 the .NET Framework, you can get the current time 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 and that is why there is a leap year every 4 years.
  1. /* ------------------------- 
  2. * Age finding code here... */  
  3.   
  4. // Create a new object  
  5. var dateOfBirth = new DateTime(1995, 2, 2);  
  6. // Get the today object  
  7. var timeSpan = DateTime.Today.Subtract(dateOfBirth);  
  8.   
  9. // Now let us stylize it a bit to make sure we get enough details.  
  10. // Divide the days by 365.25; make years  
  11. var age = (int) (timeSpan.TotalDays / 365.25);  
This preceding 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 an elder when you are reading this article.

age calculater
Age calculator. Provides the age of the user 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 that has ed for some other instance of time. Like, how much time has elapsed since a prior meeting, or how much time has ed since the last presentation and so on. In such conditions, the .NET Framework has introduced the class TimeSpan for displaying 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 TimeSpan object.

Let us see 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 ed since that specific date.
  1. /* ------------------------------------------------- 
  2. * Code for time spans for finding the elapsed time */  
  3.   
  4. // Create instances  
  5. var preTimeHour = new DateTime(2015, 2, 10);  
  6. var preTimeYear = new DateTime(2014, 8, 29);  
  7.   
  8. // Get the time elapsed for these times  
  9. var elapsedHours = DateTime.Now.Subtract(preTimeHour).Hours;  
  10. var elapsedYear = DateTime.Now.Subtract(preTimeYear).Days;  
The preceding code would find the values that we've appended (.Hours and .Days). The following output was printed in this case (in my instance of time, yours will differ).

elapsed time counter

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 various social platforms that the time of the social activity is shown, in a format like “<variable> minutes ago”. That is the similar thing discussed previously, but a slight difference. That is, in this case now the 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 see a few examples to consider and see how the .NET Framework would let us know how much time has been consumed since that time instance.
  1. // Create a new generic list instance  
  2. var list = new List<DateTime>();  
  3.   
  4. // Add a few instances to the list  
  5. list.Add(new DateTime(2014, 2, 2));  
  6. list.Add(new DateTime(2015, 1, 19));  
  7. list.Add(new DateTime(2015, 2, 12));  
  8. list.Add(new DateTime(2015, 2, 12, 1, 0, 0));  
  9. list.Add(new DateTime(2015, 2, 12, 0, 0, 0));  
  10. list.Add(DateTime.Now);  
Now let us see what .NET rendered on the screen in the browser using these instances. In the HTML markup, I wrote another code, to find the difference of the seconds. I will share that HTML markup (in Razor syntax) that you would be interested in reading in. Provide the following markup a look:
  1. @foreach (var dateTime in list)  
  2. {  
  3.    // For each of the instance of the DateTime, check how much time has elapsed  
  4.    var seconds = (DateTime.Now - dateTime).TotalSeconds;  
  5.    <p>  
  6.       The time that has elapsed since @dateTime.ToString("MMMM dd, yyyy hh:mm:ss"is   
  7.       @if (seconds < 1)  
  8.       {  
  9.          // Zero seconds, hopefully that DateTime.Now object  
  10.          @:zero seconds, thus <i>just now</i>.  
  11.       }  
  12.       else if (seconds > 0 && seconds < 60)  
  13.       {  
  14.          // Seconds are greater than zero but less than 61 (minute)  
  15.          @:@seconds seconds.  
  16.       }  
  17.       else if (seconds > 60 && seconds < 3600)  
  18.       {  
  19.          // seconds are greater than minute but less than hour  
  20.          @:@(Convert.ToInt16(seconds / 60)) minutes.  
  21.       }  
  22.       else if (seconds > 3600 && seconds < 86400)  
  23.       {  
  24.          @:@(Convert.ToInt16(seconds / 3600)) hours.  
  25.       }  
  26.       else  
  27.       {  
  28.          @:more than a day.  
  29.       }  
  30.    </p>  
  31. }  
Now the preceding code block finds the actual time that has elapsed. The only reason that it is a long one is that it must do 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 preceding code was something like this:

working with collections
Time Span representation of the date.

Various formats of DateTime object

In our applications, we need to display the DateTime object in the format that the 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 love to read the date in the format date/month/year. Now, the .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 multiple values and parameters to change the format of the date in the format that the user wants.

Tip: Using the method I will show, you can use a string value from the database and 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 will be using to display our date in. I will use a single instance of DateTime to remove any ambiguity from your minds and to show it in various formats using those formats.
  1. /* ----------------------------------- 
  2. * The DateTime ToString() extensions */  
  3. var formats = new List<string>();  
  4. formats.Add("MMMM dd, yyyy");  
  5. formats.Add("MMMM dd, yyyy hh:mm");  
  6. formats.Add("MMMM dd, yyyy 'at' hh:mm ss");  
  7. formats.Add("MMMM dd, yy hh:mm");  
  8. formats.Add("MMMM dd, yy dddd");  
Now, the result of this string elements list would be printed, they would be used as the format for the DateTime object, for the string notation of it. I used the following HTML, to convert the date into the representative string format.
  1. @foreach (var format in formats)  
  2. {  
  3.    @:"@format" is used to render the DateTime object as, <b>@DateTime.Now.ToString(format)</b>.  
  4.    <br />  
  5. }  
The result of this (at my instance of time) was:

date time format
DateTime object various formats.

This is the article of mine to explain the DateTime object in ASP.NET websites.

Points of Interest

The DateTime object is available in the .NET Framework and can be used in ASP.NET websites. 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 objects to perform various functions in ASP.NET websites that require the use of date, such as calendar applications. DateTime is an effective way of completing your project, instead of using integer data values for month, date and year and so on.

You can 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.

 

Up Next
    Ebook Download
    View all
    Learn
    View all