Working on Date and Time in C#

Vishal Pathak
Abhima C# Programming
2 min readMar 18, 2022

To work on Date and Time there is one struct in C# as DateTime. Today we will be going through most used properties and methods of DateTime struct.

Photo by Dominik Vanyi on Unsplash

So let’s see some useful properties and methods in DateTime struct.

Get the current date and time:-

So to get the current date and time we normally use Now property of DateTime. But to get the time in UTC format we use UtcNow. In below example we showed both the properties.

Get the date and time in datetime format:-

So to get the date and time in datetime format we have multiple ways to do it. Passing value in the constructor and Using TryParse method.

To get the date and time through constructor we have to pass integer values in year, month, date, minute, seconds. It will return the date and time according to the parameter values given in the constructor.

By using TryParse method we can convert the string date into date time by just passing the string and one out DateTime object. So this method returns boolean value and assigns converted datetime to out DateTime object.

We can use AddDays() function on the DateTime object to Add or Subtract the days from the given object value. To Subtract we can give negative integer value to it.

We can change the DateTime into different format as well to do this we have to just provide the string format in to ToString() method while converting datetime into string.

We can use AddYears() method to add years to the datetime object.

Below are some other important properties.

  1. Year:- Gets the year of the date.
  2. Day:- Gets the day of the date.
  3. DayOfWeek:- Gets the day of the week.
  4. Hour:- Gets the hour from the DateTime object.
  5. Month:- Gets the Month from the DateTime object.

Bhagavad Gita Verse of the Day

भक्त्या त्वनन्यया शक्य अहमेवंविधोऽर्जुन |
ज्ञातुं द्रष्टुं च तत्त्वेन प्रवेष्टुं च परन्तप || 54||

bhaktyā tv ananyayā śhakya aham evaṁ-vidho ’rjuna
jñātuṁ draṣhṭuṁ cha tattvena praveṣhṭuṁ cha parantapa

BG 11.54: O Arjun, by unalloyed devotion alone can I be known as I am, standing before you. Thereby, on receiving My divine vision, O scorcher of foes, one can enter into union with Me.

--

--

Vishal Pathak
Abhima C# Programming

love ❤ coding, solving some industry problems technologies: JavaScript, C#, Angular, PLSQL, Docker Want to learn: Python, Go language, AI, ML and Cloud