Working with Date and Time in C#.Net

C#.Net provides DateTime structure that offers many useful methods and properties for date and time calculations. The range of DateTime is between 01/01/0001 12:00:00 AM to 31/12/9999 11:59:59 PM.

DateTime return various date/time elements:

[csharp]
DateTime d1 = DateTime.Now;
listBox1.Items.Add("Year\t\t: " + d1.Year);
listBox1.Items.Add("Month\t\t: " + d1.Month);
listBox1.Items.Add("Day\t\t: " + d1.Day);
listBox1.Items.Add("DayOfWeek\t: " + d1.DayOfWeek);
listBox1.Items.Add("DayOfYear\t: " + d1.DayOfYear);
listBox1.Items.Add("Hour\t\t: " + d1.Hour);
listBox1.Items.Add("TimeOfDay\t: " + d1.TimeOfDay);
listBox1.Items.Add("Minute\t\t: " + d1.Minute);
[/csharp]

Output:

Date and Time in C#.Net

Formatting and parsing date and time

Following are different ways for Formatting and parsing date and time.

[csharp]
listBox1.Items.Add(DateTime.Now.ToString());
listBox1.Items.Add(DateTime.Now.ToShortDateString());
listBox1.Items.Add(DateTime.Now.ToLongDateString());
listBox1.Items.Add(DateTime.Now.ToShortTimeString());
listBox1.Items.Add(DateTime.Now.ToLongTimeString());
[/csharp]

Output:

Formatting and parsing Date in C#.Net

 

Adding or Subtracting from Dates and Times

The C# DateTime provides a number of methods for adding or subtracting date and times from a DateTime instance.
Substracting days from current date.

[csharp]
DateTime dt = DateTime.Today.AddDays(-2);
string strDate = dt.ToString("dd / MM / yy");
listBox1.Items.Add(strDate);
[/csharp]

Add days to the current date.

[csharp]
DateTime tomorrow = DateTime.Today.AddDays(1);
string strDate = tomorrow.ToString("dd / MM / yy");
listBox1.Items.Add(strDate);
[/csharp]

Calculating the time after 30 minute (adding minutes to the current time.)

[csharp]
DateTime later = DateTime.Now.AddMinutes(30);
string strDate = later.ToString("dd / MM / yy, hh : mm ");
listBox1.Items.Add(strDate);
[/csharp]

output:

Adding or Subtracting Date in C#.Net

 

To calculate total number of days between two dates

To get the days in between two dates in DateTime format, we need to Use TimeSpan object which is the result of date subtraction.

[csharp]
DateTime d1 = DateTime.Now.AddDays(6);
DateTime d2 = DateTime.Now.AddDays(-2);
TimeSpan t = d1 – d2;
double diff = t.TotalDays;
[/csharp]

To get the days in between two dates in DateTime format, we need to Use TimeSpan object which is the result of date subtraction.

About the Author

has written 6 posts.

I work as a freelance consultant and is passionate about taking challenges in all technologies. I am a software consultant and trainer with 8+ years experience in designing, development and maintaining enterprise wide applications. My interests involves Programming, Website development, Learning and Teaching subjects related to Computer Science and Information technology.

Copyright © 2017 http://www.techzoo.org. All rights reserved.
Proudly powered by WordPress. Developed by 7Tech Solutions