Dates and times
Work with DateTime, TimeSpan, DateOnly and time zones: create dates, do date maths, format and parse them safely.
DateTime for a moment in time and TimeSpan for a length of time.
Creating dates
DateTime now = DateTime.Now; // local date and timeDateTime today = DateTime.Today; // today at 00:00DateTime utc = DateTime.UtcNow; // universal time (for storing)var handover = new DateTime(2026, 12, 15, 17, 30, 0); // year, month, day, h, m, s Console.WriteLine(handover.DayOfWeek);Console.WriteLine(handover.ToString("dd-MM-yyyy HH:mm"));Tuesday 15-12-2026 17:30
Date maths
var start = new DateTime(2026, 11, 8);DateTime due = start.AddDays(45); // also AddMonths, AddYears, AddHours…TimeSpan left = due - start; // subtracting dates gives a TimeSpan Console.WriteLine(due.ToString("d MMM yyyy"));Console.WriteLine(left.TotalDays);Console.WriteLine(due > start); // dates compare normally TimeSpan shift = TimeSpan.FromHours(8.5);Console.WriteLine(shift); // 08:30:0023 Dec 2026 45 True 08:30:00
Custom format specifiers
| Specifier | Meaning | Example |
|---|---|---|
yyyy / yy | ||
MM / MMM / MMMM | ||
dd / ddd / dddd | ||
HH / hh | ||
mm / ss | ||
tt |
Parsing user input safely
using System.Globalization; string text = "15-12-2026";if (DateTime.TryParseExact(text, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime d)) Console.WriteLine($"Valid: {d:dddd}");else Console.WriteLine("Please use dd-MM-yyyy");Valid: Tuesday
TryParseExact you state the format, so there is no guessing.
DateOnly and TimeOnly (.NET 6+)
DateOnly birthday = new DateOnly(1999, 5, 14); // just a date, no timeTimeOnly opens = new TimeOnly(9, 30); // just a time of dayConsole.WriteLine(birthday.AddYears(27).ToString("d MMM yyyy"));14 May 2026
Time zones in one rule
DateTime.UtcNow for timestamps, .ToLocalTime() when displaying, and DateTimeOffset when you must keep the original offset (like +05:30 for India).
Measuring how long code takes
using System.Diagnostics; var sw = Stopwatch.StartNew();LoadModel(); // the work you want to timesw.Stop();Console.WriteLine($"Loaded in {sw.ElapsedMilliseconds} ms");Stopwatch, not DateTime.Now subtraction, for timing: it is far more precise. It is the first tool for performance work.
Show a hint
Show the solution
var date = new DateTime(2026, 12, 1);int worked = 1; // the start day counts as day 1while (worked < 90){ date = date.AddDays(1); if (date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday) worked++;}Console.WriteLine(date.ToString("dddd, d MMMM yyyy"));Monday, 5 April 2027
Remember
DateTimeis a moment;TimeSpanis a duration; both are immutable.Use AddDays/AddMonthsand subtraction for date maths.MM= month,mm= minutes; parse withTryParseExactand a known format.Store UTC, display local; time code with Stopwatch.