Date with C#

Dates and times are very important in software development.  C# has built-in methods for manipulating dates and time and we will discuss those with the help of this example.

using System;
namespace DatesAndTimes
{
class Program
{
static void Main(string[] args)
{
DateTime myValue = DateTime.Now;
Console.WriteLine(myValue.ToString());
Console.WriteLine(myValue.ToShortDateString());
Console.WriteLine(myValue.ToShortTimeString());
Console.WriteLine(myValue.ToLongDateString());
Console.WriteLine(myValue.ToLongTimeString());
Console.WriteLine(myValue.AddDays(3).ToLongDateString());
Console.WriteLine(myValue.AddHours(3).ToLongTimeString());
Console.WriteLine(myValue.AddDays(-3).ToLongDateString());
Console.WriteLine(myValue.Month);
DateTime myBirthday = new DateTime(1969, 12, 7);
Console.WriteLine(myBirthday.ToShortDateString());
TimeSpan myAge = DateTime.Now.Subtract(myBirthday);
Console.WriteLine(myAge.TotalDays);
Console.ReadLine();
}
}
}

At first, we have declared the date object and initialized it with the present date and time values when the application is running. Now the following methods convert that in different string formats as given in the output. Similarly, the AddDays(), AddHours() adds up the number of days and hour respectively. We can grab parts of a date and time like we printed the month of the date time object myValue by calling myValue.Month.
That was all going on with the current date time, but if we want to make a date time object with custom values we can do this.DateTime myBirthday = new DateTime(1969, 12, 7)
To calculate the difference between two dates we can call the Subtract() method.

Leave a Reply

Your email address will not be published. Required fields are marked *