Working with Dates in .NET

See related: .NET examples

.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.

Dim dt1 As DateTime = Now
Dim dt2 As DateTime = dt1.AddDays((New Random).NextDouble() * 2)
Dim ts As TimeSpan = 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: 12/03/2021 20:03:54 minus 12/02/2021 10:20:34
DAYS: 1
HOURS: 9
MINUTES: 43
SECONDS: 20
MILLISECONDS: 308
Total Hours: 33
Total Minutes: 2023


Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site.
OK