C# Datetime: How to Handle Time Constructs Efficiently

c# datetimeC# was developed by Microsoft as a competitor to Sun Microsystem’s Java, after the latter prevented Microsoft from making changes to Java. In the 6 years since it’s been around, the language has been gaining ground steadily and may one day even be as popular as Java. Microsoft has invested millions of dollars promoting and developing C#. There is a pretty high demand in the market for developers with C# skills, so it really helps to learn the language. If you’re familiar with C or C++, or even Java, you’ll be able to pick up C# easily. This course on C# is the best place to get started. It teaches you everything a good C# programmer should know.

C# is an object oriented, modern programming language. You will find it easier to learn C# if you’ve studied any object oriented language in the past (even if it wasn’t Java). C# can do everything that Java can do. You will find C# used in games, Windows applications, compilers, XML web service applications, database apps and client-server applications. At the moment, Microsoft has released version 2.0 of the language. In fact, we have a course to help you develop your very first Android app using C#.

In this tutorial, we’re going to take a quick look at the DateTime structure in C#. It requires some familiarity with the basics of C#. If you’re new to C#, we recommend you first take this beginners course.

C# DateTime

You will need to work with times and dates a lot as a programmer. In C#, you can use the DateTime structure, and its methods and properties, to handle time and use it in your programs. For example, you can use DateTime to get the current system time, the date yesterday or even to print the first day of the year.

Now let’s take a few sample programs (displaying some of the different methods available in DateTime) to help you get a basic understanding of the structure.

Example 1: Program to Write the Date to the Console

First, let’s write a sample program to accept the value of a date:

using System;
class Example
{
static void Main()
{
    DateTime date1 = new DateTime(2014, 4, 20);
    Console.WriteLine(date1);
}
}
Output: 4/20/2014 12:00:00 AM

We just created a new DateTime structure with three distinct parameters and then asked C# to print it. The result was the date and time stored in the DateTime structure displayed in the MM/DD/YYYY format. Notice that the time is 12 am by default.

Example 2: How to Write the Time to the Console

using System;
class Example
{
static void Main()
{
DateTime date1 = new DateTime(2014, 4, 20, 8, 30, 0);
Console.WriteLine(date1. ToString () );
}
}
Output: 4/20/2014 8:30:00 AM

In this example, we added three additional time parameters that changed the output. Note that you have to separate all the parameters by a comma. Also, note that the time has three parameters and all of them must be filled (with 0, if necessary).

Changing the Culture to Change the Format of the displayed Date

By default, the date will be displayed in the MM/DD/YYYY format. You can change that format to DD/MM/YYYY with the IFormatProvider method to change the “culture”, which is a term that is used for a collection of different formats in different places. The MM/DD/YYYY format is en-US, for example. To make it to the en-GB for the United Kingdom (DD/MM/YYYY), for example, just add the method, like in the sample program below:

using System;
class Example
{
static void Main()
{
DateTime date1 = new DateTime(2014, 4, 20, 8, 30, 0);
Console.WriteLine(date1.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("en-GB")));
 }
}
Output: 20/4/2014 8:30:00 AM

The program is almost identical to the one we wrote earlier, except for the addition of a new culture. Note how that changes the way the date is displayed.

Some applications allow a user to enter the time in both a DD/MM/YYYY and a MM/DD/YYYY format, depending on the location of the user. This ability to change the format is very useful if you’re going to be designing applications which will have users from all over the world. You can explore more about setting the date in C# with this course.

Checking the Time Today

How do you check what time it is today, that is, what is the current system time? Use the following program:

using System;
class Example
{
    static void Main()
    {
                Console.WriteLine("The Date and Time today is {0}", DateTime.Today);
}
}
Output: The Date and Time today is 4/25/2014 12:00:00 AM

We used the DateTime.Today method to check the current system date and time. If you’d prefer a more visual approach to learning this, check out our C# course for video based lessons.

Checking the Date and Time Yesterday

Now that you know what the day was today, how do you find out what the day was yesterday? Or the day before? You can use the AddDays method, like in the program below:

using System;
class Example
{
    static void Main()
    {
                DateTime yes = GetDateYesterday();
                Console.WriteLine("The Date and Time Yesterday was {0}", yes);
    }
    static DateTime GetDateYesterday()
    {
                return DateTime.Today.AddDays(-1);
    }
}
Output: The Date and Time today is 4/25/2014 12:00:00 AM
The Date and Time Yesterday was 4/24/2014 12:00:00 AM

The AddDays method can be used to move the DateTime time value up by one unit (which is one day). Because we used a negative AddDay value, we were able to get the date and time one day backwards to yesterday, and then we printed it. Learn more about it with this amazing C# course.

Checking the Date and Time the Day Before

In this sample program, we’ll write to the console the date and time day before:

using System;
class Example
{
    static void Main()
    {
                DateTime yes = GetDateYesterday();
                Console.WriteLine("The Date and Time Day Before was {0}", yes);
    }
    static DateTime GetDateYesterday()
    {
                return DateTime.Today.AddDays(-2);
    }
}
Output: The Date and Time Day Before was 4/23/2014 12:00:00 AM

This program is very similar to the one above; except for a single change: we added a negative one to the parameter of the AddDays method. If we wanted to find the date tomorrow, we could’ve added 1. For the date day after, we could have added 2. If we wanted to find the date next year, we could have added 365! Try typing this program yourself and experiment by adding different values to the AddDays parameter.

Some of the other methods that you will want to get familiar with include the compare method (compares two dates), subtract (subtract a specified date and time value from the DateTime), IsLeapYear (a method to find out whether the current day is a leap year or not), FromFileTime (used to conver file time in Windows to equivalent local time), ToString (the ToString method converts DateTime represented in integers to equivalent string value) and Parse (converts string date and time to integer representation). For a full list of all the possible methods that you can use with DateTime, check out the official documentation. To use DateTime in C# effectively, you will have to get familiar with most of these methods. Happy Exploring!