Dates and Times in C# .NET

At some stage of your programming career, you'll need the ability to manipulate dates and time. A typical example would be a database programme where you want to record when an entry was made, especially if it's an order for a product. Or if you want to, say, calculate how many days it's been since an order was placed.
Start a new project for this. Add a button to your new form, and double click it to get at the code.
An inbuilt structure you can use to manipulate dates is called DateTime. Add this to you button code:
DateTime theDate;
theDate = DateTime.Now;
MessageBox.Show( theDate.ToString() );

After setting up a DateTime variable called theDate, we have this line:
theDate = DateTime.Now;
The Now property returns the current system date and time of your computer, wherever you are in the world.
The third line in our code converts the DateTime into a string and then displays it in a message box. When the code is run, and the button clicked, the message box will be something like this:
Message Box with a Date and Time
This is the date in UK format (day first, then month), followed by the current time (hours, minutes and seconds).
You can also have this, instead of Now:
theDate = DateTime.Today;
And even this
theDate = DateTime.UtcNow;
Utc is something called Coordinated Universal Time, or International Atomic Time.
Try all three in your code and see how they differ.
To get at just the year, or the month, or the day, take a look at the IntelliSense list when you type the dot after DateTime:

A list of Date and Time Methods and Properties in C#
If you click on Day to highlight it, you'll see that it is an Integer:
To use this, then, you can set up a new integer variable and hand it the day:
theDate = DateTime.UtcNow;
int theDay = theDate.Day;
The Month and Year are also Integers, so the code is similar:
int theMonth = theDate.Month;
int theYear = theDate.Year;
You can also convert your date to a string, and use something called a Format Provider. Try this code:
DateTime theDate = DateTime.UtcNow;
string custom = theDate.ToString("d");
When you run your programme and click the button, the date displays in this format:
Change the "d" in the code above to "D" (capital D instead of lowercase). When you run the code, the date is displayed like this:
12 November 2013
Here's a list of letters you can use, and what they will display. Try a few and see for yourself:
A Table of Date and Time formats in C# .NET
Another thing you can do with DateTime is to specify a format. Type the following:
DateTime firstDate = new DateTime
After the final "e", type a round bracket. You should see this:
The DateTime Class in C#
There are 12 different ways to use the DateTime structure. Each one is giving you the option of a date/time format. Examine option 4 of 12:
Specify a Date
You can just type some numbers here:
DateTime firstDate = new DateTime(2013, 01, 14);
What you'll get back is the Date you specified. But you'll also get the time as a series of zeros:
A date displayed in a message box
If you want to calculate the difference between one date and another, then a more precise structure is used with DateTime - TimeSpan. Here's how to use it:
DateTime firstDate = new DateTime(2013, 01, 14);
DateTime secondDate = DateTime.Parse("1 Feb 2013");
TimeSpan dateDiff;
dateDiff = secondDate.Subtract(firstDate);
MessageBox.Show("Date diff:" + dateDiff.ToString() );
The first line sets up a date: the 14th of January 2013. The second line sets up a date in a different way:
DateTime secondDate = DateTime.Parse("1 Feb 2013");
After the dot of DateTime, we're using Parse. In between the round brackets of Parse, simply type your date between double quotes.
When you subtract one date from another, the answer is returned as a TimeSpan structure. This uses similar methods and properties as DateTime. One of the options is Subtract:
TimeSpan dateDiff;
dateDiff = secondDate.Subtract( firstDate );
After typing a date then a dot, use the Subtract method. In between the round brackets of Subtract, you need another date - the one you're trying to subtract. When the code is run, it will calculate the difference between the two dates.
You can also add date and time values to ones you already have. Examine this code:
firstDate = firstDate.AddDays(30);
MessageBox.Show( firstDate.ToString("D") );
Now we're using AddDays after our firstDate variable. In between the round brackets of AddDays, type how many days you want to add.
When the IntelliSense list appears, have a look at other date and time values you can add: AddMonths, AddYears, etc.

Getting at the values on other Forms

Turn your Form2 into a Change Case dialogue box, just like ours below:
A Change Case form
When the OK button is clicked, we want the text in the text box on Form1 to change case, depending on which of the three options was chosen.
The problem we face is that the text box is private to Form1, and can't be seen from outside it. If you tried to refer to the text box from Form2, you'd just get errors.
One solution is to set up a public static variable, of type TextBox. You then assign textBox1 to this new variable.
So add the following to Form1:
public static TextBox tb = new TextBox();
This creates a new TextBox object called tb. Add the line just under your Form variable, and your coding window will look like this:
C# code to create a new text box
Notice that we've deleted the message box code, and went back to the original. That's because we don't need the message box anymore. Delete yours as well.
Now that we have a TextBox object, we can assign our text box on form one to it. In the Form Load event of Form1, add the following line:
tb = txtChangeCase;
(The easiest way to bring up the code stub for the Form Load event is to double click a blank area of the form in design view.)
Here's what all the Form1 code looks like now:
Form Load Event
When the main form (Form1) loads, the text box will now be available to Form2.
So double click your OK button on Form2 to bring up its code stub. Enter the following:
string changeCase = Form1.tb.Text;
We're setting up a string variable called changeCase. The contents of this new string variable will be the Text from the text box called tb on Form1.
To change the case of the text, we can use string methods for two of them: Uppercase and Lowercase. Like this:
changeCase = changeCase.ToUpper();
changeCase = changeCase.ToLower();
Unfortunately, C# .NET does not have a direct string method to change text to Proper Case (or Title case as it's also know). Proper Case is capitalising the first letter of each word. For example, "This Is Proper Case".
In order to get Proper Case, you have to reference two System namespaces. One called Globalization and one called Threading. Add the following to the very top of the coding window:
using System.Globalization;
using System.Threading;
The code window will then look something like this:
Add two using statements
Now that we have these two references, the next thing to do is to set up something called a CultureInfo object:
CultureInfo properCase = Thread.CurrentThread.CurrentCulture;
The CurrentCulture tells you information about the various language options of your particular country. Our CultureInfo object is called properCase.
That's not the end of it, though! You also need a TextInfo object:
TextInfo textInfoObject = properCase.TextInfo;
It's this TextInfo object that has the methods we need. We're setting up a TextInfo object called textInfoObject. We're handing it the TextInfo property of our properCase CultureInfo object.
Finally, we can change the case:
changeCase = textInfoObject.ToTitleCase( changeCase );
The TextInfo object has a method called ToTitleCase. In between the round brackets of the method, you type what it is you want to convert.
Hopefully, in future versions of C#, they'll add an easier way to convert to Proper Case!
To get which of the options on our Form2 was chosen, we can add a series of if … else statements:
C# code to change case
So we're just checking to see which radio button was selected. We're then doing the case conversion.
To put the changed text into the text box on Form1, add the following line:
Form1.tb.Text = changeCase;
Add the line just before your DialogResult line. The full code for the button should be this
Full C# code for form 2
Run your programme and test it out. Click your button to bring up Form2. Select the Upper Case option and then click your OK button. You should find that the text in txtChangeCase on your main form will now be in uppercase.

The next section of the C# course deals with Dates and Times.