<style> .reveal-up, .reveal-left, .reveal-right, .reveal-stagger > * { opacity: 1 !important; transform: none !important; } </style>
  1. Learn
  2. C#
  3. Working with data
All lessons in this course

Lesson 29 of 60 13 minIntermediate

Dates and times

Work with DateTime, TimeSpan, DateOnly and time zones: create dates, do date maths, format and parse them safely.

Deadlines, delivery dates, log timestamps, project durations: almost every business program handles dates. .NET gives you DateTime for a moment in time and TimeSpan for a length of time.

Interactive

DateTime explorer

var d = new DateTime(2026, 11, 8, 9, 30, 0);
d.Year2026
d.Month11
d.Day8
d.DayOfWeekSunday
d.DayOfYear312
d.Hour9
DateTime.IsLeapYear(d.Year)False
DateTime.DaysInMonth(...)30
var later = d.AddDays(30);
Tuesday, 8 December 2026 09:30
TimeSpan span = later - d;
span.Days30
span.TotalHours720
span.TotalMinutes43200
d.ToString(format)
"dd-MM-yyyy"08-11-2026
"yyyy-MM-dd"2026-11-08
"dd/MM/yy"08/11/26
"d MMM yyyy"8 Nov 2026
"dddd"Sunday
"HH:mm"09:30
"hh:mm tt"09:30 AM
"yyyy-MM-ddTHH:mm:ss"2026-11-08T09:30:00

Creating dates

Create.cs
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"));
Output
Tuesday
15-12-2026 17:30

Date maths

Maths.cs
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:00
Output
23 Dec 2026
45
True
08:30:00

Custom format specifiers

SpecifierMeaningExample
yyyy / yyyear2026 / 26
MM / MMM / MMMMmonth number / short / full name11 / Nov / November
dd / ddd / ddddday / short / full weekday08 / Sun / Sunday
HH / hhhour 24-h / 12-h17 / 05
mm / ssminutes / seconds30 / 00
ttAM / PMPM

Parsing user input safely

Parse.cs
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");
Output
Valid: Tuesday

Is “03/04/2026” the 3rd of April or the 4th of March? It depends on the culture. With TryParseExact you state the format, so there is no guessing.

DateOnly and TimeOnly (.NET 6+)

DateOnly.cs
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"));
Output
14 May 2026

Time zones in one rule

Store and calculate in UTC; show in local time. Servers, users and databases can be in different time zones. 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

Stopwatch.cs
using System.Diagnostics; var sw = Stopwatch.StartNew();LoadModel();                            // the work you want to timesw.Stop();Console.WriteLine($"Loaded in {sw.ElapsedMilliseconds} ms");

Use Stopwatch, not DateTime.Now subtraction, for timing: it is far more precise. It is the first tool for performance work.

Quick check

What type do you get from date2 - date1?

Quick check

Which format prints 8 November 2026 as “08-11-2026”?

Practice

A project starts on 1 Dec 2026 and takes 90 working days (Monday to Friday only). Write a loop that finds the finish date and prints it as “dddd, d MMMM yyyy”.

Show a hint

Start from the start date, add one day at a time, and only count days whose DayOfWeek isn’t Saturday or Sunday.

Show the solution
Solution.cs
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"));
Output
Monday, 5 April 2027

Remember

  • DateTime is a moment; TimeSpan is a duration; both are immutable.
  • Use AddDays/AddMonths and subtraction for date maths.
  • MM = month, mm = minutes; parse with TryParseExact and a known format.
  • Store UTC, display local; time code with Stopwatch.
0 of 60 lessons completed