C# DateTime Tutorial: Working With Date & Time In C# With Example

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 7, 2024

This Tutorial Will Explain All About C# DateTime Class. You will Learn to Work with C# DateTime Format Including Timer, Stopwatch and Sleep Methods:

Time and date are widely used in several software projects. We often deal with date and time objects while writing different programs.

Date time has various applications like getting current date-time, adding a timestamp to variable/file names, using date time for validation, etc. With so many applications you can easily guess how important the date-time object is for programmers.

=> Check Out The In-Depth C# Training Tutorials Here

C# DateTime

How To Initialize The C# DateTime Object?

DateTime is a Struct in the System namespace. It helps the programmers retrieve information about system date, time, month, year or even the day of the week. It also allows users to perform operations on the retrieved date-time values.

Let’s have a look at a simple program by initializing a new DateTime object. When we initialize a new object we will need to pass certain parameters to set date value.

namespace ConsoleApp1
{
class Program
       {
static void Main(string[] args)
               {
                     // year, month, date
                     DateTime dt = new DateTime(2018, 11, 05);
                     Console.WriteLine(dt.ToString());
                     Console.ReadLine();
               }
     } 
 }
 

Here, we have passed the date as 05, month as 11 and year as 2018. This will set the data time instance to the parameter provided by us. After the initialization, we have printed the initialized object to console by converting it into a string.

The output of the above program will be:

11/5/2018 12:00:00 AM

In the above output, you can see that as we have not provided any time value, hence the DateTime object has used the default time.

Properties Of The DateTime Object

DateTime object offers a number of different properties to help users to retrieve data about the date and time object.

Here we will discuss few important date time properties:

Day

Day property retrieves the set date of the date-time object. It returns an integer value and doesn’t accept any argument.

Syntax:

int date = dt.Day;

Month

Month property retrieves the set month of the date-time object. It returns an integer value and doesn’t accept any argument.

Syntax:

int month = dt.Month;

Year

Year property retrieves the set year of the date-time object. It returns an integer value and doesn’t accept any argument.

Syntax:

int yr = dt.Year;

Day of the Week

Day of the week property retrieves the integer value of the day of the week from the set date-time object. It also requires casting to accept integer value. It doesn’t accept any argument.

Syntax:

int dayWeek = (int)dt.DayOfWeek;

Day of Year

Day of year property retrieves the day of the year from the set value of the date in the date-time object. It returns an integer value and doesn’t accept any argument.

Syntax:

int dayYear = dt.DayOfYear;

Hour

Day property retrieves the set date of the date-time object. It returns an integer value and doesn’t accept any argument.

Syntax:

int hour = dt.Hour;

Minute

Min property retrieves the minute value from the set date of the date-time object. It returns an integer value and doesn’t accept any argument.

Syntax:

int min = dt.Minute;

Second

Second property retrieves the second value from the set value of the date-time object. It returns an integer value and doesn’t accept any argument.

Syntax:

int sec = dt.Second;

Let’s have a look at a simple program to retrieve these values.

namespace ConsoleApp1
{
class Program
       {
static void Main(string[] args)
               {
                     // year, month, date
                     DateTime dt = new DateTime(2018, 11, 05);
                     int date = dt.Day;
                     int month = dt.Month;
                     int yr = dt.Year;
                     int dayWeek = (int)dt.DayOfWeek;
                     int dayYear = dt.DayOfYear;
                     int hour = dt.Hour;
                     int min = dt.Minute;
                     int sec = dt.Second;
                    Console.WriteLine(date);
                    Console.WriteLine(month);
                    Console.WriteLine(yr);
                    Console.WriteLine(dayWeek);
                    Console.WriteLine(dayYear);
                    Console.WriteLine(hour);
                    Console.WriteLine(min);
                    Console.WriteLine(sec);
                    Console.ReadLine();
              }
       }
}

The output of the above program will be:

Date : 5
Month : 11
Year : 2018
Day of the week : 1
Day of the year : 309
Hour : 0
Minute : 0
Second : 0

In the above program, we have set the date value as 05/11/2018. Thus, we can see that the system has fetched the same values but when we look at the time part we will see the default value is 0. It is because, we haven’t set any time value and thus the system automatically assigned default values to an hour, minute and second.

What Is Date Formatting?

Different applications and different programmers may require a different format of date for their usage. So, date formatting is used to format the date for numerous requirements. DateTime also offers different formatting options to get your date in the desired format.

There are different specifiers designated to offer you the desired format of the date. Here we will discuss a few of the popular ones:

Short Time Format

It displays a simple time format with an hour and minutes suffixed by AM or PM. It is denoted by “t” in a small case.

The output format will be: 12:00 PM

Long Time Format

It displays extended time format with hour, minute and second suffixed by AM or PM. It is denoted by “T” in the upper case.

The output format will be: 12:13:12 PM

Short Date

It displays a simple date format in MM/DD/YYYY format. It is denoted by the alphabet “d” in a small case.

The output format will be: 11/05/2018

Long Date

It displays extended date format with the day, month, day and year. It is denoted by the alphabet “D” in the upper case.

The output format will be: Monday, November 05, 2018

Day/Month

It displays date format with Date and Month. It doesn’t contain the year details. It is denoted by the alphabet “M” in the upper case.

The output format will be: 5-Nov

Month/Year

It displays the date format with Month and Year. It doesn’t contain date details. It is denoted by the alphabet “Y” in the upper case.

The output format will be: November, 2018

Let’s have a look at these in detail with the help of a simple program.

namespace ConsoleApp1
{

 class Program
{
static void Main(string[] args)
{
 // year, month, date
 DateTime dt = new DateTime(2018, 11, 05);
 //short time
 Console.WriteLine("Short time : {0}",dt.ToString("t"));
//Long Time
 Console.WriteLine("Long time : {0}", dt.ToString("T"));
 //Short Date
 Console.WriteLine("Short Date : {0}", dt.ToString("d"));
 //Long Date
 Console.WriteLine("Long date : {0}", dt.ToString("D"));
//Day / Month
Console.WriteLine("Day with month : {0}", dt.ToString("M"));
//Month / Year
 Console.WriteLine("Month with year : {0}", dt.ToString("Y"));

Console.ReadLine();
 }
 }
}

The output of the above program will be:

Short time : 12:00 AM
Long-time : 12:00:00 AM
Short Date: 11/5/2018
Long date: Monday, November 5, 2018
Day with month: November 5
Month with year : November 2018

In the above program, we have initialized the value of the date in the first line and then we have tried to use the same value to obtain different formats.

How To Get Current Date Time?

DateTime object contains a number of different methods to access system time. The “Now” method allows you to get the current system time/date and even allows you to operate on it.

The syntax to get current time will be:

DateTime today = DateTime.Now;

Once we have defined and stored now into a DateTime object. We can easily convert it to string to get the current date-time or we can even change the format of the date by using the specifiers discussed above.

C# Timer

The timer in C# allows the programmers to set a time interval to execute a certain set of code or instruction in a recurring manner. It is very useful in case your application specification requires you to execute an event after every certain interval.

For example, during the implementation of a data back-up application.

Let us have a look at a simple program to implement a timer:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
using System.Timers;
namespace ConsoleApp1
{
    class Program
    {
        private static Timer timer;
        static void Main(string[] args)
        {
             timer = new System.Timers.Timer();
            timer.Interval = 2000;
            timer.Elapsed += OnTimerEvent;
            timer.AutoReset = true;
            timer.Enabled = true;
            Console.WriteLine("The timer will start logging now... ");
            Console.ReadLine();
        }
        private static void OnTimerEvent(Object source, System.Timers.ElapsedEventArgs e) {
           
               Console.WriteLine("Time logged: {0}", e.SignalTime.ToString("T"));
        }
    }
}

So, if you run this program it will keep on logging the time after every 2 seconds.

In the above program, we first initialized the System.Timer. Then we set the interval time for the timer. Here we have kept the interval as 2000 milliseconds, you can provide any implementation as per your requirement. Once the time interval has been elapsed we need to run some instruction by calling some method.

Here we called “OnTimerEvent” every two seconds. The method will accept two parameters, the first one is “object” and another one is “ElapsedEventArgs”.

We also need to reset the timer every time when it reaches an interval and we also need to enable it. Hence, both auto-reset and timer enable are marked as true. Then we write our custom message to the console and also add a readline to make sure that the console remains open till user intervention.

C# Stopwatch

The stopwatch is used in C# to measure time. It is very useful in benchmarking code performance during code optimization. It can be used to perform continuous monitoring of the code/application performance and to keep a check of any performance downgrade.

The stopwatch can accurately measure the time elapsed during an event and is the perfect choice for timing any event in the program. Stopwatch class is defined in the System.Diagnostics namespace and needs to be instantiated for usage. This makes it quite useful for applications that require multi-threading. The event calls can be executed by using thread.sleep method.

What Is Sleep Method?

The sleep method is used to pause the running thread for a specific time span. It accepts time in milliseconds. Sleep is very useful in a multi-threading environment where you want one thread to stop to make way for other threads to complete their execution.

The syntax for C# Sleep method is:

System.Threading.Thread.Sleep(1000);

Now we have learned about sleep and other stopwatch class.

Let’s create a simple stopwatch program to understand things more clearly.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
namespace ConsoleApp1
{
    class Program
    {
               static void Main(string[] args)
        {
            Console.WriteLine("Press Enter to start the stopwatch");
            Console.ReadLine();
            // Create a new Stopwatch.
            var stopwatch = Stopwatch.StartNew();
            Console.WriteLine("Stopwatch started...");
            Console.WriteLine("Press Enter to stop the stopwatch and show time");
            Console.ReadLine();
            // Write result.
            Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
            Console.ReadLine();
        }
        
    }
}

Output

The output of the above program will be something like this:

simple stopwatch program

The last line shows the time elapsed between the start and stops of the stopwatch.

In the above program, we defined a variable stopwatch in which we stored the instance of Stopwatch class. We used the StartNew() method. The startnew method creates a new instance each time it is called, hence it is very useful when we want to start the stopwatch from the beginning.

The Elapsed property of the stopwatch allows the user to record the time span of the run. In the end, we simply printed the elapsed time to the console.

Conclusion

Date time, timer, sleep, and stopwatch all are used in C# programming language for satisfying various purposes. A DateTime object is used to gather information about the date and time of the system or to set a custom date and time for use for a particular application requirement.

The timer, on the other hand, is used to set a time interval between the execution of certain commands or events.

Sleep is the part of System.Threading and is used to pause or halt the execution for a certain time interval. This allows the programmers to start another thread in the multi-threading environment while the previous thread is paused.

The stopwatch can be used to measure the performance or time spent on the execution of a certain event. It can offer a precise measurement of the time elapsed or ticks that can be used to keep application performance in check.

=> Explore The Entire Series Of C# Training Tutorials Here

Was this helpful?

Thanks for your feedback!

Leave a Comment