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.UtcNowfor server-side or multi-region apps - Use
DateTimeOffsetfor precise timezone tracking - Avoid using
DateTime.Nowin 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
| Concept | Purpose |
|---|---|
DateTime.Now | Current local date and time |
DateTime.UtcNow | Current universal (UTC) time |
TimeSpan | Represents a duration or time difference |
ToString(format) | Format a date/time string |
AddDays/Hours | Add/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.