Working with Dates and Time in C#

Handling dates and time correctly is a vital part of many C# applications โ€” from scheduling tasks and logging activity to displaying formatted timestamps. This session covers how to use DateTime, format dates, calculate durations, and avoid common errors.

Youโ€™ll learn the tools needed to work with time zones, delays, and future/past events in a reliable, professional way.


โฐ What Is DateTime?

DateTime is a built-in C# structure used to represent a specific moment in time โ€” including the date and the time of day.

DateTime now = DateTime.Now;
Console.WriteLine(now); // Outputs: current local date and time

๐Ÿ”น Getting the Current Date and Time

DateTime localNow = DateTime.Now;       // Local date and time
DateTime utcNow = DateTime.UtcNow; // Coordinated Universal Time
DateTime today = DateTime.Today; // Todayโ€™s date at 00:00

๐Ÿ”ธ Formatting Dates

Use ToString() with format specifiers to control how dates appear:

DateTime birthday = new DateTime(1990, 5, 10);

Console.WriteLine(birthday.ToString("dd/MM/yyyy")); // 10/05/1990
Console.WriteLine(birthday.ToString("MMMM dd, yyyy")); // May 10, 1990
Console.WriteLine(birthday.ToString("yyyy-MM-dd HH:mm")); // 1990-05-10 00:00

โž• Adding or Subtracting Time

DateTime tomorrow = DateTime.Now.AddDays(1);
DateTime oneHourLater = DateTime.Now.AddHours(1);
DateTime lastWeek = DateTime.Now.AddDays(-7);

๐Ÿ”„ Calculating Time Differences

Use TimeSpan to find the difference between two dates:

DateTime start = new DateTime(2025, 1, 1);
DateTime end = DateTime.Now;

TimeSpan difference = end - start;
Console.WriteLine($"Days since start: {difference.Days}");

๐ŸŒ Time Zones and UTC

  • Use DateTime.UtcNow for server-side or multi-region apps
  • Use DateTimeOffset for precise timezone tracking
  • Avoid using DateTime.Now in logging unless you control the server region

๐Ÿงช Practice Exercise

Create a simple program that:

  • Asks the user for their date of birth
  • Calculates their exact age in years, months, and days
  • Displays how many days are left until their next birthday

๐Ÿ“š Summary

ConceptPurpose
DateTime.NowCurrent local date and time
DateTime.UtcNowCurrent universal (UTC) time
TimeSpanRepresents a duration or time difference
ToString(format)Format a date/time string
AddDays/HoursAdd/subtract time from a DateTime

๐Ÿ“ฌ Want help applying date/time logic in your real-world project? Whether you’re scheduling, logging, or calculating ages โ€” Iโ€™m here to help bring your C# apps to life with time-aware features.