Working with DateTime in C#

In this article, we will discuss working with DateTime in C#. A DateTime object is commonly used for handling Date and time in .NET(Core). Let’s dive into the DateTime object.

You can improve your stringBuilder performance by following our below article.

Improve StringBuilder performance in C#

1. How to create a DateTime in C#?

We can create DateTime objects in multiple ways. A DateTime object can have multiple properties Iike Date, Time, Localization, culture, milliseconds, and kind.

 // Empty DateTime  
            DateTime emptydateTime = new DateTime();

            // Create a DateTime from date and time  
            DateTime dateofbirth = new DateTime(1996, 22, 10, 8, 11, 25);

            // Create a DateTime from a String  
            string dateString = "22/10/1976 8:11:25 AM";
            DateTime dateFromString =
                DateTime.Parse(dateString, System.Globalization.CultureInfo.InvariantCulture);
            Console.WriteLine(dateFromString.ToString());

            // Just date  
            DateTime onlyDate = new DateTime(2002, 10, 18);

            // DateTime from Ticks  
            DateTime onlyTime = new DateTime(1000000);

            // DateTime with localization  
            DateTime datetimeWithKind = new DateTime(1996, 22, 10, 8, 11, 25, DateTimeKind.Local);

            // DateTime with date, time and milliseconds  
            DateTime datetimeWithMilliseconds = new DateTime(2022, 01, 28, 6, 31, 45, 100);

DateTime Properties in C#:

I have described above some of the properties of DateTime Like Date, Time, and localization. But apart from these properties in C# DateTime object have many other properties that can help in our code logic. I have listed below some properties of DateTime and provided some descriptions of each.

DayOfWeek: Gets the name of the day in a week.

DayOfYear: Gets the day of the year.

TimeOfDay: Gets the time of the day.

Today: Gets the today date value with the 12:00:00 time value.

Now: Gets the date and time value of right now.

UtcNow: Gets the Date and time value in the (UTC).

Ticks: The number of ticks that represent the date and time of this instance. The value is between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks.

Kind: Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither.

Here is the code example that can express the properties in a more practical manner.

DateTime dummydate = new DateTime(2022, 1, 5, 8, 12, 27);
            Console.WriteLine("day:{0}", dummydate.Day);
            Console.WriteLine("month:{0}", dummydate.Month);
            Console.WriteLine("year:{0}", dummydate.Year);
            Console.WriteLine("hour:{0}", dummydate.Hour);
            Console.WriteLine("minute:{0}", dummydate.Minute);
            Console.WriteLine("second:{0}", dummydate.Second);
            Console.WriteLine("Millisecond:{0}", dummydate.Millisecond);

            Console.WriteLine("day of week:{0}", dummydate.DayOfWeek);
            Console.WriteLine("day of year: {0}", dummydate.DayOfYear);
            Console.WriteLine("time of day:{0}", dummydate.TimeOfDay);
            Console.WriteLine("tick:{0}", dummydate.Ticks);
            Console.WriteLine("kind:{0}", dummydate.Kind);

Here is the output of the above code.

 working with DateTime in C#

Adding and subtracting of DateTime in C#:

In C# DateTime object provide us methods to add and subtract date and time. TimeSpan plays a vital role in adding and subtracting dates and times.

Let’s have a code example to better understand this.

DateTime day = DateTime.Now;
TimeSpan month = new System.TimeSpan(30, 0, 0, 0);
DateTime DayAfterMonth = day.Add(month);
DateTime DayBeforeMonth = day.Subtract(month);
Console.WriteLine("{0:dddd}", DayAfterMonth);
Console.WriteLine("{0:dddd}", DayBeforeMonth);

The DateTime object also has methods to add years, days, hours, minutes, and seconds. Let’s have a code sample to understand.

DateTime day = DateTime.Now;
 // Add Years and Days  
day.AddYears(5);
day.AddDays(6);
// Add Hours, Minutes, Seconds, Milliseconds, and Ticks  
day.AddHours(5.45);
day.AddMinutes(20);
day.AddSeconds(50);
day.AddMilliseconds(400);
day.AddTicks(1000);

Like, add methods DateTime structs don’t have similar subtract methods. To subtract DateTime we have to create DateTime or TimeSpan first and then we can subtract DateTime. I have given some expamles below.

DateTime dateofbirth = new DateTime(2000, 10, 20, 12, 15, 45);
            DateTime anotherdate = new DateTime(2000, 2, 6, 13, 5, 15);

            // TimeSpan with 10 days, 2 hrs, 30 mins, 45 seconds, and 100 milliseconds  
            TimeSpan timespan = new TimeSpan(10, 2, 30, 45, 100);

            // Subtract a DateTime  
            TimeSpan diff1 = dateofbirth.Subtract(anotherdate);
            Console.WriteLine(diff1.ToString());

            // Subtract a TimeSpan  
            DateTime diff2 = dateofbirth.Subtract(timespan);
            Console.WriteLine(diff2.ToString());

            // Subtract 10 Days  
            DateTime daysSubtracted = new DateTime(dateofbirth.Year, dateofbirth.Month, dateofbirth.Day - 10);
            Console.WriteLine(daysSubtracted.ToString());

            // Subtract hours, minutes, and seconds  
            DateTime hms = new DateTime(dateofbirth.Year, dateofbirth.Month, dateofbirth.Day, dateofbirth.Hour - 1, dateofbirth.Minute - 15, dateofbirth.Second - 15);
            Console.WriteLine(hms.ToString());

Format of DateTime in C#:

Microsoft does a great job to provide DateTime formats in C#. We can format DateTime in any possible string form according to requirement. Let’s see the code example.

GetDateTimeFormats: Converts the value of this instance to all the string representations supported by the standard date and time format specifiers.

DateTime datetime = new DateTime(2002, 10, 22);
            string[] dateFormats = datetime.GetDateTimeFormats();
            foreach (string format in dateFormats)
                Console.WriteLine(format);

By running this code snippet you will get the list of all DateTime formats supported by the system.

How to find days in a month?

DaysInMonth: The number of days in a month for the specified year. For example, if the month equals 2 for February, the return value is 28 or 29 depending upon whether a year is a leap year.

int daysofmonth = DateTime.DaysInMonth(1996, 10);
Console.WriteLine(daysofmonth);

How to convert a string to DateTime in C#?

Parse: Converts the string representation of a date and time to its System.DateTime equivalent by using the conventions of the current thread culture.

string date = "2010-10-04T20:12:45-5:00";
DateTime newdate = DateTime.Parse(date);
Console.WriteLine(newdate.ToString());

Conclusion:

In this article, I have tried to cover common DateTime properties and use cases. If you have suggestion to make this post better, do not hesitate to comment below or contact us.

Leave a Reply

Related Posts

  • c# Exception Tostring vs Message – Complete Guide

  • c# Yield Exception Handling – Explained!

  • c# Excel Error 0x800a03ec – Complete Guide

  • c# get Error Message from Modelstate – Explained & Solved

  • c# Error Netsdk1005 – Solved!

  • c# Error Parsing Infinity Value – Explained & Solved!