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);| Type | Holds | Use for |
|---|---|---|
DateTime | Date + time, Kind = Local/Utc/Unspecified | General use; store as UTC |
DateTimeOffset | Date + time + UTC offset | Timestamps in APIs and databases |
DateOnly / TimeOnly | Just a date / just a time | Birthdays, opening hours |
TimeSpan | A duration | Differences, timeouts |
TimeProvider (.NET 8) | Abstraction of "now" | Unit-testable time |
Interview tip:
DateTimeis a struct (value type) and is immutable —d.AddDays(1)returns a new value, it doesn't changed. Store UTC, convert to local only for display.