Click here to Skip to main content
Click here to Skip to main content

Understanding DateTime struct in .NET Framework (using C#)

, 13 Aug 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Understanding the DateTime struct and using it inside your software to display Date and Time and to do the DateTime mathematics

Introduction

This article helps you understand what is the DateTime structure inside the .NET Framework provided by Microsoft for their Windows OS and how you can use it to display the current or custom date and time inside your software.

The declaration of this struct field is as follows:

public struct DateTime : IComparable, IFormattable, 
    IConvertible, ISerializable, IComparable<DateTime>, IEquatable<DateTime>

You can note the keyword struct in the declaration. That is to tell the compiler (and developer) that this is not a class, it is a structure.

It must be noted that DateTime struct is a direct child of the System namespace, so you just need to be using this in the C# class file to include it in your project.

using System;

Background

Many times, developers like to count the days until today since the last weekend, they want to count the age of the users on their platform and so on. This is known as "DateTime mathematics" in our language where we calculate the dates and times that have passed until now, we calculate the seconds and so on. While doing so, .NET Framework takes care of most of the things that we have to do, so we can keep focused on just the logic to get the result and not the algorithm for the DateTime objects.

In my article, I will try to explain how you can create a new DateTime object using default value (that is already built into the .NET Framework) or by using your own custom value and passing them as a parameter to the DateTime constructor.

Environment Requirements

If you're using Visual Studio in your production, then you can skip this part. This part just shows you what you need to be having before you can continue to the further sections of this article to build/run and test the demo code provided for the software that teaches you the basics.

First of all, you need to get the copy of your Visual Studio from Microsoft. You can get an Express version that is free of cost or you can get your own copy that perfectly suits you. They all compile the code for you!

After that, you will be up and running. That setup will itself install all the required software on your system and will make sure that the software that you're going to compile gets everything it needs.

Note: It will also update the .NET Framework version on your system if you're having an older version. Newer version of .NET Framework ensures new methods to work with and some security improvements too.

Overview of the DateTime struct (API)

This section of the article provides a little bit overview of the DateTime struct in the C# (.NET Framework's System namespace). I will try to explain the constructors, methods, properties of the struct.

This will not cover each and every one of them, but will be covering the basics and what you can do using them. I will try to explain and add the reference to each of the documentation on them on the MSDN library for the DateTime struct or, to whatever the class the object (or parameter) belongs to.

DateTime Constructors

This initializes the DateTime object instance and gets back to you for more execution. Example constructor that you face regularly (and in this project too) is as follows:

Signature: new DateTime(int year, int month, int date);
DateTime datetime = new DateTime(1995, 08, 29); // August 29th, 1995

But this is only one of them. There are 11 constructors provided by the System namespace that you can use depending on the reason of using DateTime object. For example, you might want to add the ticks or milliseconds to the code too. You can use this one:

Signature: new DateTime(int year, int month, int date, int hour, int minute, int seconds);
DateTime dateTime = new DateTime(1995, 08, 29, 00, 00, 00); // August 29th, 1995, 12AM

This one was the second one and it adds the time too so that you can add the time. There are some other functions where you can further more add the Calender type too and so on. But remember, it is just a short way to add more properties to the object. You can even create a single DateTime object and then add hours, minutes and seconds too. But doing it this way is more efficient and a recommended way.

A list of the constructors can be found here:

DateTime Fields

Fields are objects or values contained in class or struct which you can use to get the values for the Class itself, and not the object. They define the properties of the Class or Struct (in our case Struct) itself and are common for each of the object instances too. For example, int might have many object instances but each of them has the same MaxValue field.

There are two DateTime fields that are:

public static readonly DateTime MaxValue;
public static readonly DateTime MinValue;

They're static, because they're not changing throughout the execution and throughout the lifeline and you do not need to create a new instance of the DateTime using the DateTime constructor you can easily access them like this:

DateTime.MaxValue; // returns DateTime and not int or string

They're readonly so that you cannot use it on the left side of the assignment operator. Simple as that!

For more on DateTime fields, read http://msdn.microsoft.com/en-us/library/system.datetime_fields(v=vs.110).aspx.

DateTime Methods

Like all other classes and structs, DateTime also provides a variety of methods (functions) that the objects that belong to this struct can perform. You can navigate to the MSDN library and search for the entire gallery. But I will like to discuss the basic ones (leaving behind the ones discussed below in the code, don't want to confuse you).

First method of the DateTime object is the Add function.

dateTime.Add(TimeSpan param1); // returns DateTime

This function adds a new TimeSpan (for instance, an hour or a day, etc.) to the dateTime object and returns the result. You can use it to add days and get what will be the DateTime value from now to the days that you added. There are other methods like AddDays and AddHours etc. too.

IsLeapYear is a function that gets whether this year is a leap year* or not. This is a bool returning function so it will either return a true or a false. It will go like:

dateTime.IsLeapYear(); // returns false for 2014, but true for 2016 or 2012

*Leap year is a year, where February gets 29 days. https://en.wikipedia.org/wiki/Leap_year

DateTime also provides a method to convert from other type to DateTime object. For example, if you have got a string value that indicates a time and date, you can convert it to the DateTime. You can use the Parse method for that. It throws an error if you pass an invalid date and time object. It must be like this:

Signature: new DateTime.Parse("mm-dd-yyyy hh:mm:ss");
DateTime dateTime = DateTime.Parse("08-29-1995 00:00:00"); // returns DateTime

As I have stated below, using the Convert.ToDateTime(string param1) is a better and easy way to convert from String to the DateTime class. Use that method. Use this only if necessary!

You can use Subtract method to remove the TimeSpan from the DateTime object. It is just an opposite to the Add function.

ToLongString and similar functions (three used below in the code) are just used to format the DateTime object and show it in the human (user) friendly version instead of the computer friendly version. You don't have to be worried about it. It is just a fancy-writer function.

Like every class or struct, there is also a ToString function. But this one has some extra functions too. It stylizes your DateTime object if you pass some parameter. For example in my code, I have passed a simple string to convert my DateTime object to a stylized string with the result.

// create a new instance
DateTime dateTime = DateTime.Now;
// convert it to the string, but with parameter
dateTime.ToString("MMMM dd, yyyy hh:mm s's'"); // August 29th, 1995 12:00 00s AM

I am sorry I am waiting eagerly for my birthday so I am using this much 29th August around.

You can use many other characters to get the result on the screen. The list of the characters can be captured from the MSDN.

There are many other functions that you can use to minimize the coding hours. Since you can do that yourself too, but using the functions is a more efficient way of doing the coding because .NET Framework developers have written a lot of code to make our software better and our software development process shorter.

For more on functions, see http://msdn.microsoft.com/en-us/library/system.datetime_methods(v=vs.110).aspx.

DateTime Properties

These are the propeties of the objects (and not the class or struct itself). Each of the classes can have it differently, and they depend on the object instance itself and not the class or struct.

DateTime has very basic properties that help you not go and check the Calender and do the DateTime maths on it. But they're designed to get you started by writing just a line of code.

DateTime properties are all non-static instead of three properties, which are static in nature.

DateTime.Now;
DateTime.Today;
DateTime.UtcNow;

All of the others require you to have atleast an instance to work on because they depend on the instance created. They're Day, DayOfWeek, Year, etc. properties of the DateTime object. For instance,

DateTime dateTime = DateTime.Now; // static
dateTime.Year; // non-static and returns 2014 (int)

There are many other properties that just work on the current instance and provide you with either date, time, year and week values, etc.

For more, see http://msdn.microsoft.com/en-us/library/System.DateTime_properties(v=vs.110).aspx.

DateTime Operators

Actually, when the .NET Framework developers built DateTime struct, they knew there was something unusual about the DateTime, that had to be done. Because adding 1 into 1st August had no meaning. But adding one day to 1st august had a meaning. So, they used the operator overloading approach and changed the way operators were actually used.

You don't need to go in depth and learn it, it is intuitive and you can understand what might happen when I do this:

dateTime + dateTime1

This adds the dateTime1 object to dateTime but in the DateTime math way.

They just changed the way you calculated the dates or created a logic to check whether the ticket is valid until today and changed the way you used the subtract operator in the integer objects. This section is not for us. .NET Framework has done enough to make sure we just use simple math operators and the DateTime class works on them as we want it to happen.

For more, read http://msdn.microsoft.com/en-us/library/ff986512(v=vs.110).aspx.

Downloading the Project (... and Running It)

You can download the project from the link at the top of this article. After that, you need to be pasting it to your "Documents\Visual Studio 2013\Projects\" folder and then run the Solution file. Visual Studio will itself open up and then you can choose to build the project and test it or continue to edit it and make it better as you like.

Project Code and Details

This project was built for beginners who get confused with the DateTime objects and working with them. It is a pure basic conceptual tutorial so don't think this might solve a rocket science question. The project I am going to explain here is enough for you to get the basic understanding of the DateTime and you don't even have to download the source code to test it but if you want to do it, go ahead and download the source code.

I will explain the C# logic behind the software and will leave the XAML code untouched.

Using DateTime in your Code

You can use DateTime structure inside your code for the software in many ways. You can either ask the compiler to generate a new instance of this structure using the current date and time from the system where the program is currently executing or you can get a custom value from the user (or yourself) and then pass it to the DateTime constructor* and get the value on to your screen.

*Constructor: Whenever a class or struct is created, its constructor is called. Constructor creates a new instance of that struct or class.

DateTime like all other struct and classes has constructor, and it has 11 constructors depending on your needs. You can use any of them and they'll return a new instance of the DateTime struct.

As I said, you can get the current DateTime of the time, for this, you can use the following code to get the current Date and Time on the your computer:

var date = DateTime.Now; // current time and date

It will return the current time to you, right now for me it will be: "08/14/2014 01:47:10 AM". Yours would be different.

After this is done, you can do the DateTime math on the instance.

Getting Started with the Project

In the software I am using, you will see two global variables on top of the code just below the class declaration like this:

private string type = "current"; // a conditional value only
private DateTime dateTime; // a DateTime object for the entire class I am working with

These two variables are used across the software that is why they're declared inside the class and not inside any function. If I declared it inside any method, I would have had to write it again breaking the DRY "Don't Repeat Yourself" rule of programming.

After this new method is called, that gets the value of the DateTime and then does the DateTime mathematics on it, to call the next function and write the data to the User Interface. It goes like this:

public void GetDateTime()
{
    if (type == "current")
    {
        // current date time is required.
        dateTime = DateTime.Now;
        this.GetDateTimeFormats(dateTime);
    }
    else
    {
        try
        {
            string value = CustomDateTime.Text;
            dateTime = Convert.ToDateTime(value);

            this.GetDateTimeFormats(dateTime);
        } 
        catch (Exception ex) 
        {
            MessageBox.Show("There was an error converting the string to datetime. 
            Try the DateTime in this format mm-dd-yyyy hh:mm:ss\n\n..and remember, 
            no double quotation marks in the value.");
        }
    }
}

This gets the value and makes sure what type of date and time is required by the user. If he wants to see the current date time, it gets the current value you can see in the if block. Otherwise, it will go to the else block and will try to ask the user to provide a custom value. This method initializes the dateTime variable that we're having globally in the class. See the code block above.

In this block, I am having a try catch block because if the user tries to put a value that is not a valid date time string format, then the .NET Framework would throw an InvalidFormatException. To reduce chances of bad exceptions in our UI, we use try catch block, so am I. This will make sure that we pass on the correct and valid date time string so that .NET can know how to handle it.

I am using Convert.ToDateTime(string parameter) to convert the string into a DateTime object this time. It is most simplest method to convert the string into DateTime. Otherwise, you can also use DateTime.ParseExact and all other methods to convert from String to DateTime too. But since you are a beginner, I would advise you use this simple method as you don't have to work with Cultures in .NET, etc.

Tip: Don't use the double quotation marks in the value, just provide the data in the format mm-dd-yyyy hh:mm:ss. For example, 08:29:1995 00:00:00 would result in August 8, 1995 12:00:00 AM (my birthday).

As you can see, there is another method being called, that method is used to populate the UI of the software and show the data to the user. This method is not tricky, and has the most of the code to populate the UI. In this method, we use some of the function calls on DateTime to change their display (Long or Short type) and to check their properties (Length) and so on. The code block goes like:

public void GetDateTimeFormats(DateTime time)
{
    // set the UI values from the DateTime provided in the time parameter.

    dateTimeLength.Text = time.ToString().Length.ToString() + " characters.";
    dateTimeLongString.Text = time.ToLongDateString();
    dateTimeLongTimeString.Text = time.ToLongTimeString();
    dateTimeShortString.Text = time.ToShortDateString();
    dateTimeShortTimeString.Text = time.ToShortTimeString();
    if (type == "custom")
    {
        if (CustomDateTimeFormat.Text != "")
        {
            dateTimeToString.Text = time.ToString(CustomDateTimeFormat.Text);
        }
        else
        {
            dateTimeToString.Text = time.ToString("MMMM dd, yyyy hh:mm ss's'");
        }
    }
    else
    {
        dateTimeToString.Text = time.ToString("MMMM dd, yyyy hh:mm ss's'");
    }
        dateTimeShownAs.Text = "DateTime that you're currently working with is: " + 
                                time.ToString();

    this.ElapsedTime(time, new DateTime(1995, 8, 29));
}

This code gets all the data for the DateTime object and then passes it to the XAML where the controls are, so that the user can view the code that's going on.

You will notice some function like ToLongDateString() and ToShortTimeString(). I will leave these to you to explore the code and look for yourself but remember, these are just a few methods to change the view of the DateTime object and they return a string to you.

Here in this code, a keyword this is being used, although this is not a part of DateTime struct, but I would like to give you a little detail about it. This "this" keyword refers to the current context that you are referring to. In this code, it is referring to the class MainWindow in our code.

Once again, another call has been made and now the code has to go to a new method and do what the methods calls it to do. This method as the name states gets the Elapsed time between two dates. The first parameter is the current date and the second is the date until which we want to get the time elapsed.

Its declaration and the body is as:

public void ElapsedTime(DateTime time1, DateTime time2)
{
    TimeSpan timeSpan = time1 - time2;
    dateTimeElapsedTime.Text = "Hours elapsed are: " + timeSpan.Hours.ToString();
}

This block is the shortest of all of the code blocks but I did that on purpose, because I don't want to spare any time trying to tell you how many days pass when next Fridays come as you guys already know. What I want to do here is to teach you a new method to create a new DateTime instance.

When I used custom DateTime class, I used the Convert thing and then got the string converted to the DateTime but this time I am using int values to create a new instance. As I already mentioned, there are 11 constructors for DateTime (as stated by MSDN in the link above) and among them there is a constructor where you can pass the integer values and the .NET does your work and converts them into a new DateTime instance for you to work with.

For example, in the code that I used...

new DateTime(1995, 8, 29);

...this creates a new instance of the DateTime object. You can see I am using the new keyword to declare that I want a new DateTime, but what might be the value for it? That is what I am passing down to the constructor. The constructor I am using is like this:

public DateTime(
    int year,
    int month,
    int day
)

First parameter is for year, second for month and third one for the day. You need to be accurate for these, a small error would cause a change in years. After this, you can get your DateTime object and work with it like I have done. Like code creates a new datetime that refers to the 29th August, 1995 12 AM, the date of my birth. Code then executes and provides me with the hours that have elapsed until now and so on and so forth.

Using the Software (Tutorial)

You can use the software now if you want to and see how the DateTime objects are created and what you get as the display value when you pass one what type of value.

Main Page

Main page of the software is set up to use the System date time as the DateTime object and provide you with the details of the current date time. Some other properties and functions are also called so that you can see the DateTime in different styles too.

Main Page

This was the main page, you can see it used the current date time for me!

Custom DateTime page

You can navigate to the custom DateTime page by clicking on the right side where it is written.

Custom DateTime page

You are asked to write the valid date time value, otherwise you'll get the following error message:

Error Custom DateTime

You can see I have tried to input wrong input and the software tells me to input a correct value so that it can process it.

Valid DateTime value (No Formatting)

Add a valid value and you'll get this:

Custom DateTime (No formatting)

This above view is the default setting but a custom date time object. You can see that the second Inbox box is left empty and still the code is executing that is because the software a default (I wrote this in the software and is the default, otherwise there is no such default value that will provide this value in .NET Framework) value that is, "MMMM dd, yyyy hh:mm:ss's'".

Valid value and a Result on Screen (With Formatting)

You can even pass your own formatting string and get the desired string.

Custom date (Custom Formatting)

You can see in the last line, there is only August written because I only asked the compiler to provide me with "MMMM" month value of the DateTime instance.

Try the software to test around the values in DateTime struct.

Points of Interest

Actually, this article was written as a whole and then I was myself forced to delete it and write a new project in Visual Studio and then write a new article with new source code because I thought DateTime was a class. But MSDN says it is a struct, to just not confuse the developers, I removed the ambiguity by removing all the previous content and recreating it.

So, I learnt that DateTime is a struct and not a Class object.

Second thing I learnt was that you can subtract one date from other and the result is stored in TimeSpan object which can then accept the DateTime methods and provide you with hours years that have elapsed until now.

History

  • First post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Afzaal Ahmad Zeeshan
Student De Codes
Pakistan Pakistan
Hi, my name is Afzaal Ahmad Zeeshan. I am a Pakistani, student, Ahmadi Muslim kid. I live in Rabwah and I am here since I was ~3years old. I have done my matriculation with major subjects for Science and Intermediate in Engineering.
 
I started learning programming when I was 15 and wrote small application that would get me double (not the data type) of the int value I would provide it with. In the beginning, I started Web applications, using ASP.NET when I was 16 and I really didn't know ASP.NET is written in C#, all I knew was that there is something called Razor syntax. I created simple web applications like Say hello to a friend, Add a friend in your list and get the elder among them. After craming the ASP.NET codes, I finally realized that there is no way to write application by cramming the API. So, I went learning, I learnt Visual C#, Java, Visual C++, started to learn Assembly but gave up in the middle, will restart this.
 
I have written some projects for my friends, I have made some web applications for cousins, I have developed a few applications for my cell phone, for desktop. I have developed an HTML keyboard for websites, like a On-Screen Keyboard, A Login system using simple C# code and JSON files. I am planning to write a Database system that would be much much much less costly than MS SQL. I am author at many blogs and teach programming to new developers to the extent that I have learnt programming.
 
I am never found complaining, I am self teaching, I am polite to elders, I accept my mistakes without criticizing the person who found a bug in me. I listen to Eminem, more than I listen to my girl. I am logical, you can make me quite my logically proving me wrong. Otherwise our dicussion might be a never ending loop.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
Questionvery useful PinprofessionalSanthoshobject13-Aug-14 21:52 
AnswerRe: very useful PinprofessionalAfzaal Ahmad Zeeshan13-Aug-14 22:26 
AnswerRe: very useful PinprofessionalAfzaal Ahmad Zeeshan19-Aug-14 4:58 
GeneralRe: very useful PinprofessionalSanthoshobject21-Aug-14 8:09 
AnswerRe: very useful PinprofessionalAfzaal Ahmad Zeeshan21-Aug-14 9:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150326.1 | Last Updated 14 Aug 2014
Article Copyright 2014 by Afzaal Ahmad Zeeshan
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid