articles » current » dot-net » working-with-dates

.NET: Working with Dates

Working with the Date object and the TimeSpan object written in C#

.NET makes working with dates incredibly easy. To find the difference between two dates, simply subtract them like subtracting two integers. The result of the operation is a timespan object.

DateTime dt1 = DateTime.Now;
DateTime dt2 = dt1.AddDays(new Random().NextDouble() * 2);
TimeSpan ts - dt2 - dt1;
lblDates.InnerHtml = dt2 + " minus " + dt1;
lblDays.InnerHtml = ts.Days;
lblHours.InnerHtml = ts.Hours;
lblMinutes.InnerHtml = ts.Minutes;
lblSeconds.InnerHtml = ts.Seconds;
lblMillisec.InnerHtml = ts.Milliseconds;
lblTotalHours.InnerHtml = ts.Days * 24 + ts.Hours + ts.Minutes / 60;
lblTotalMinutes.InnerHtml = ts.Days * 24 * 60 + ts.Hours * 60 + ts.Minutes;

DATES: 3/26/2022 3:57:47 PM minus 3/26/2022 11:03:27 AM
DAYS: 0
HOURS: 4
MINUTES: 54
SECONDS: 20
MILLISECONDS: 499
Total Hours: 4
Total Minutes: 294


This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE