Working with DateTime in C#

20 Jul 2023 Balmiki Mandal 0 C# (C Sharp)

Using DateTime in C#

The DateTime class in C# provides a simple way to work with dates and times. It enables developers to use absolute values for date and time, and calculate date/time intervals between two points. In this blog post, we’ll explore how to use DateTime in C#, and some of its most useful features.

Creating DateTime Objects

A DateTime object can be created using the DateTime constructor, which takes a DateTime.Ticks parameter:


DateTime myDate = new DateTime(DateTime.Now.Ticks);

The DateTime.Now property returns the current date and time in UTC format. Alternatively, we can create a DateTime object using one of the DateTime static methods: DateTime.Parse, DateTime.TryParse or DateTime.FromBinary. Examples are shown below:


// Parsing strings to DateTime
DateTime date1 = DateTime.Parse("2020-04-07");

// From DateTime.Now
DateTime date2 = DateTime.Now;

// From binary
DateTime date3 = DateTime.FromBinary(0x8000000000000000);

Manipulating DateTime Objects

Once we have a DateTime object, we can easily manipulate them and perform various operations. For example, we can add or subtract days, hours, minutes, months and years from a DateTime object, using the Add() method or the Subtract() method:


DateTime date1 = DateTime.Now;
DateTime date2 = date1.AddDays(30);
DateTime date3 = date2.Subtract(TimeSpan.FromMinutes(30));

We can also get the difference between two dates using the Subtract() method, and get the day, month or year of a given date:


// Difference between two dates
TimeSpan difference = date2.Subtract(date1);

// Get day
int day = date1.Day;

// Get month
int month = date2.Month;

// Get year
int year = date3.Year;

Conclusion

In this blog post, we explored how to create and manipulate DateTime objects in C#. We’ve seen how easy it is to create DateTime objects and perform operations like adding or subtracting days, hours, minutes, months and years. We also saw how to get the difference between two dates and retrieve day, month or year of a given date. If you need to work with dates and times in your application, DateTime is a great choice.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.