Roadmap › C# Language — Basics to Advanced › Module: Getting Started
Lessons in this course (38)

8. DateTime, DateOnly, TimeSpan and time zones

BasicMediumLesson 8 of 38
csharp
DateTime now = DateTime.Now;          // local time of the machine
DateTime utc = DateTime.UtcNow;       // UTC — store and compare in UTC
DateTime d = new DateTime(2026, 10, 24, 9, 30, 0);
DateTime tomorrow = DateTime.Today.AddDays(1);

TimeSpan gap = new DateTime(2026, 12, 31) - DateTime.Today;   // difference = TimeSpan
Console.WriteLine($"{gap.TotalDays:N0} days left");
TimeSpan timeout = TimeSpan.FromSeconds(30);

Console.WriteLine(d.ToString("yyyy-MM-dd HH:mm"));   // 2026-10-24 09:30 (custom format)
Console.WriteLine(d.ToString("D"));                   // long date in current culture
Console.WriteLine(d.ToString("O"));                   // ISO 8601 round-trip: 2026-10-24T09:30:00.0000000

if (DateTime.TryParseExact("24/10/2026", "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsed))
    Console.WriteLine(parsed.DayOfWeek);              // Saturday

DateOnly birthday = new(1991, 5, 14);                 // .NET 6+: date without time
TimeOnly opening = new(9, 0);                         // time without date
DateTimeOffset placed = DateTimeOffset.UtcNow;        // instant + offset — best for timestamps across time zones

var india = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");   // "Asia/Kolkata" on Linux (.NET 6+ accepts both)
DateTime indiaTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, india);
TypeHoldsUse for
DateTimeDate + time, Kind = Local/Utc/UnspecifiedGeneral use; store as UTC
DateTimeOffsetDate + time + UTC offsetTimestamps in APIs and databases
DateOnly / TimeOnlyJust a date / just a timeBirthdays, opening hours
TimeSpanA durationDifferences, timeouts
TimeProvider (.NET 8)Abstraction of "now"Unit-testable time

Interview tip: DateTime is a struct (value type) and is immutable — d.AddDays(1) returns a new value, it doesn't change d. Store UTC, convert to local only for display.