Dates and times show up in nearly every real-world application, and C#’s DateTime and TimeSpan types give you everything you need to parse, format, and calculate them correctly.
This collection of 25 C# DateTime exercises covers formatting dates for display, calculating age and durations, adding or subtracting time, and handling calendar quirks like leap years automatically.
Each exercise includes a Practice Problem, Purpose, Hint, and a full Solution with Explanation, so you avoid common date-handling mistakes in your own projects.
Also, See: C# Exercises with 22 topic-wise sets and 620+ practice questions.
What You’ll Practice
- Formatting: Custom
DateTimeformat strings. - Parsing:
DateTime.Parse()andDateTime.TryParse(). - Arithmetic:
.AddDays(),.AddMonths(), andTimeSpandifferences. - Calendar Logic: Leap years, days in a month, and day-of-week calculations.
+ Table Of Contents (25 Exercises)
Table of contents
- Exercise 1: Display the Current Date and Time
- Exercise 2: Format a Date as a Custom String
- Exercise 3: Extract Individual Date and Time Components
- Exercise 4: Find the Day Number Within a Year
- Exercise 5: Parse a String into a DateTime
- Exercise 6: Count the Days Until Christmas
- Exercise 7: Calculate Yesterday and Tomorrow
- Exercise 8: Calculate a Person’s Age
- Exercise 9: Compare Two Dates
- Exercise 10: Add Business Days to a Date
- Exercise 11: Check if a Year Is a Leap Year
- Exercise 12: Find the First and Last Day of a Month
- Exercise 13: Calculate the Time Difference Between Two Dates
- Exercise 14: Find All Fridays in a Month
- Exercise 15: Convert Between Local Time, UTC, and a Time Zone
- Exercise 16: Check if Two Date Ranges Overlap
- Exercise 17: Find the Start and End of a Day
- Exercise 18: Calculate an Invoice Due Date
- Exercise 19: Find the Next Occurrence of a Weekday
- Exercise 20: Use DateOnly and TimeOnly Instead of DateTime
- Exercise 21: Measure Execution Time with a Stopwatch
- Exercise 22: Find the Nth Weekday of a Month
- Exercise 23: Convert Between DateTime and a Unix Timestamp
- Exercise 24: Parse a Non-Standard Date Format Exactly
- Exercise 25: Detect Daylight Saving Time Gaps and Overlaps
Exercise 1: Display the Current Date and Time
Practice Problem: Write a program to display the current date and time, the current date only, and the current day of the week.
Purpose: This exercise helps you practice the difference between DateTime.Now, which includes the time component, and DateTime.Today, which represents only the date with the time set to midnight.
Given Input: None, the program reads the system’s current date and time directly.
Expected Output:
Current Date and Time = 7/13/2026 10:42:07 AM Current Date Only = 2026-07-13 Current Day of Week = Monday
Note: since this program reads the live system clock, the actual output will differ every time it runs, reflecting whatever the current date and time happen to be.
▼ Hint
- Use
DateTime.Nowto get the current date and time together, including hours, minutes, and seconds. - Use
DateTime.Todayto get just the date portion, with the time always set to midnight. - Read the
DayOfWeekproperty off either value to get the current day as an enum, which prints as its name automatically.
▼ Solution & Explanation
Explanation:
DateTime.Now: Returns the current local date and time, including hours, minutes, and seconds.DateTime.Today: Returns the current date with the time component always set to midnight, useful when only the calendar date matters.now.DayOfWeek: Reads the day of the week as aDayOfWeekenum value, which automatically displays as a readable name like Monday.
Exercise 2: Format a Date as a Custom String
Practice Problem: Take the current date and print it in the following formats: MM/dd/yyyy, dddd, dd MMMM yyyy, and yyyy-MM-dd HH:mm:ss (ISO 8601 standard).
Purpose: This exercise helps you practice using custom format strings inside string interpolation to control exactly how a DateTime value is displayed.
Given Input: date = October 25, 2026
Expected Output:
MM/dd/yyyy = 10/25/2026 Full Format = Sunday, 25 October 2026 ISO 8601 = 2026-10-25 00:00:00
▼ Hint
- Place a colon followed by the format string directly inside the interpolation braces, for example
{date:MM/dd/yyyy}. ddddandMMMMprint the full day and month names, while lowercaseddand uppercaseMMprint zero-padded numeric values.
▼ Solution & Explanation
Explanation:
{date:MM/dd/yyyy}: Formats the date as a two-digit month, two-digit day, and four-digit year separated by slashes.{date:dddd, dd MMMM yyyy}: Combines the full weekday name, the day, the full month name, and the year into a single readable sentence.{date:yyyy-MM-dd HH:mm:ss}: Produces the ISO 8601 style format, with 24-hour time always shown even when the date has no explicit time component.
Exercise 3: Extract Individual Date and Time Components
Practice Problem: Given a specific DateTime object, extract and print its individual properties: Year, Month, Day, Hour, Minute, Second, and Millisecond.
Purpose: This exercise helps you practice reading the individual numeric components off a DateTime value instead of treating it only as a single formatted string.
Given Input: moment = March 15, 2026, 14:30:45.250
Expected Output:
Year = 2026 Month = 3 Day = 15 Hour = 14 Minute = 30 Second = 45 Millisecond = 250
▼ Hint
Each of Year, Month, Day, Hour, Minute, Second, and Millisecond is a plain read-only int property directly on the DateTime struct.
▼ Solution & Explanation
Explanation:
new DateTime(2026, 3, 15, 14, 30, 45, 250): Constructs a specific point in time using the year, month, day, hour, minute, second, and millisecond constructor overload.moment.Year,moment.Month,moment.Day: Each returns the corresponding numeric component of the date directly, with no formatting involved.moment.Hour,moment.Minute,moment.Second,moment.Millisecond: Provide the same direct access for each component of the time portion.
Exercise 4: Find the Day Number Within a Year
Practice Problem: Write a method that accepts a DateTime and returns an integer representing which day of the year it is (e.g., January 1st is 1, December 31st is 365 or 366).
Purpose: This exercise helps you practice using the built-in DayOfYear property, which already accounts for how many days each month has, including leap years.
Given Input: date = December 31, 2026
Expected Output:
Date = 2026-12-31 Day of Year = 365
▼ Hint
- The
DayOfYearproperty already does the calculation, there is no need to manually add up days per month. - Since 2026 is not a leap year, December 31 falls on day 365 rather than 366.
▼ Solution & Explanation
Explanation:
date.DayOfYear: A built-in property that returns the 1 based day number within the date’s calendar year.- Leap year awareness: The property automatically accounts for February having 29 days in a leap year, so no manual calculation is needed.
Exercise 5: Parse a String into a DateTime
Practice Problem: Parse the string "2026-12-25" into a DateTime object using DateTime.Parse() and safely using DateTime.TryParse().
Purpose: This exercise helps you practice the difference between DateTime.Parse(), which throws an exception on invalid input, and DateTime.TryParse(), which reports success or failure through a boolean instead.
Given Input: dateText = "2026-12-25"
Expected Output:
Parsed with Parse() = 2026-12-25 TryParse Succeeded = True Parsed with TryParse() = 2026-12-25
▼ Hint
DateTime.Parse(dateText)returns aDateTimedirectly, but throwsFormatExceptionif the text cannot be interpreted as a date.DateTime.TryParse(dateText, out DateTime result)returns a boolean and never throws, making it safer for unpredictable input.
▼ Solution & Explanation
Explanation:
DateTime.Parse(dateText): Converts the string directly into aDateTime, but would throw aFormatExceptionif the text were not a recognizable date.DateTime.TryParse(dateText, out DateTime safeParsedDate): Attempts the same conversion but returnsfalseinstead of throwing when the text is invalid, with the result placed in the output parameter.- When to use which:
TryParse()is generally preferred whenever the input might come from an untrusted or user supplied source.
Exercise 6: Count the Days Until Christmas
Practice Problem: Calculate and display the exact number of days left from the current date until the next Christmas Day (December 25th).
Purpose: This exercise helps you practice subtracting two DateTime values to get a TimeSpan, along with handling the edge case where the target date has already passed this year.
Given Input: today = July 13, 2026
Expected Output:
Today = 2026-07-13 Next Christmas = 2026-12-25 Days Until Christmas = 165
Note: since this program is based on DateTime.Today, the exact day count will change depending on when it is run.
▼ Hint
- Build this year’s Christmas date using
new DateTime(today.Year, 12, 25). - If that date is already earlier than today, add one year to it with
.AddYears(1)so it points to next year’s Christmas instead. - Subtracting two
DateTimevalues produces aTimeSpan, whose.Daysproperty gives the whole number of days between them.
▼ Solution & Explanation
Explanation:
new DateTime(today.Year, 12, 25): Builds a Christmas date using the current year, since the day and month are fixed but the year needs to match today.if (christmas < today) christmas = christmas.AddYears(1);: Rolls the target date forward to next year whenever this year’s Christmas has already passed.(christmas - today).Days: Subtracting the two dates produces aTimeSpan, and itsDaysproperty gives the count of full days remaining.
Exercise 7: Calculate Yesterday and Tomorrow
Practice Problem: Write a snippet that calculates yesterday’s date and tomorrow’s date relative to today.
Purpose: This exercise helps you practice using AddDays() with both positive and negative values to shift a date forward or backward.
Given Input: today = July 13, 2026
Expected Output:
Yesterday = 2026-07-12 Today = 2026-07-13 Tomorrow = 2026-07-14
Note: since this program is based on DateTime.Today, all three values will shift together depending on when it is run.
▼ Hint
Call today.AddDays(-1) for yesterday and today.AddDays(1) for tomorrow, since AddDays() accepts negative numbers to move backward in time.
▼ Solution & Explanation
Explanation:
today.AddDays(-1): Passing a negative number moves the date backward by that many days, giving yesterday’s date.today.AddDays(1): Passing a positive number moves the date forward, giving tomorrow’s date.- Immutability:
AddDays()returns a brand newDateTimerather than modifyingtodayitself, sinceDateTimevalues in C# are immutable.
Exercise 8: Calculate a Person’s Age
Practice Problem: Create a function that accepts a birthdate as a DateTime and calculates the person’s exact age in years.
Purpose: This exercise helps you practice date based age calculation that correctly checks whether the birthday has occurred yet in the current year, rather than relying on a plain year subtraction.
Given Input: birthDate = September 5, 1998
Expected Output:
Birth Date = 1998-09-05 Age = 27
Note: since CalculateAge() is based on DateTime.Today, the resulting age will change once the current date passes another birthday.
▼ Hint
- Start with a plain
today.Year - birthDate.Yearas an initial estimate of the age. - Compare
birthDate.Datetotoday.AddYears(-age), and subtract one from the age if the birthday has not yet occurred this year.
▼ Solution & Explanation
Explanation:
today.Year - birthDate.Year: Provides a rough starting estimate of the age based purely on the calendar year difference.birthDate.Date > today.AddYears(-age): Checks whether the birthday later in the calendar year has already occurred, by comparing it against today shifted back by the estimated age.age--: Corrects the estimate down by one whenever the birthday for this year has not happened yet.
Exercise 9: Compare Two Dates
Practice Problem: Write a program that takes two dates from the user and determines which date comes first, or if they are identical.
Purpose: This exercise helps you practice using DateTime.Compare() to determine the relative order of two dates without manually comparing individual year, month, and day values.
Given Input: firstDate = May 10, 2026, secondDate = August 22, 2026
Expected Output: 2026-05-10 comes before 2026-08-22
▼ Hint
DateTime.Compare(firstDate, secondDate)returns a negative number if the first date is earlier, a positive number if it is later, and zero if they are equal.- Use an
if-else if-elsechain on the comparison result to print the appropriate message.
▼ Solution & Explanation
Explanation:
DateTime.Compare(firstDate, secondDate): Returns a signed integer summarizing the relative order of the two dates, similar to how string comparison methods work.comparison < 0: Indicates thatfirstDateoccurs chronologically beforesecondDate.- Alternative: The comparison operators
<,>, and==work directly onDateTimevalues too, and would produce the same result asDateTime.Compare()here.
Exercise 10: Add Business Days to a Date
Practice Problem: Create a method AddBusinessDays(DateTime start, int days) that adds a specific number of days to a starting date, skipping Saturdays and Sundays.
Purpose: This exercise helps you practice looping day by day while checking DayOfWeek, a common requirement when calculating deadlines or delivery dates that only count working days.
Given Input: startDate = July 10, 2026 (a Friday), businessDaysToAdd = 5
Expected Output:
Start Date = 2026-07-10 (Friday) Result Date = 2026-07-17 (Friday)
▼ Hint
- Loop one day at a time using
AddDays(1), only incrementing a separate counter when the resulting day is not a Saturday or Sunday. - Keep looping until the counter reaches the requested number of business days, then return the current date.
▼ Solution & Explanation
Explanation:
while (addedDays < days): Keeps advancing one calendar day at a time until enough business days have actually been counted.result.DayOfWeek != DayOfWeek.Saturday && result.DayOfWeek != DayOfWeek.Sunday: Only increments the business day counter when the new date does not fall on a weekend.- Weekend skipped silently: Weekend days still advance the date inside the loop, they simply do not count toward the
daystotal.
Exercise 11: Check if a Year Is a Leap Year
Practice Problem: Write a program that checks if the year of a given DateTime is a leap year using built-in .NET methods.
Purpose: This exercise helps you practice using the built-in DateTime.IsLeapYear() static method instead of manually reimplementing the divisible-by-4-but-not-100-unless-400 leap year rule.
Given Input: date = June 1, 2028
Expected Output:
Year = 2028 Is Leap Year = True
▼ Hint
Call the static method DateTime.IsLeapYear(date.Year), passing in just the year as an integer rather than the whole DateTime value.
▼ Solution & Explanation
Explanation:
DateTime.IsLeapYear(date.Year): A static method that takes a plain year number and returns whether it qualifies as a leap year under the Gregorian calendar rules.- Why 2028 qualifies: 2028 is divisible by 4 and not divisible by 100, so it is a leap year with February having 29 days.
Exercise 12: Find the First and Last Day of a Month
Practice Problem: Given any DateTime, find the exact date of the first day of that month and the last day of that month.
Purpose: This exercise helps you practice combining AddMonths() and AddDays() to find month boundaries without needing to know how many days each individual month has.
Given Input: date = February 17, 2026
Expected Output:
Given Date = 2026-02-17 First Day of Month = 2026-02-01 Last Day of Month = 2026-02-28
▼ Hint
- Build the first day directly with
new DateTime(date.Year, date.Month, 1). - Get the last day by moving one month forward from the first day and then stepping back a single day with
AddMonths(1).AddDays(-1).
▼ Solution & Explanation
Explanation:
new DateTime(date.Year, date.Month, 1): Reuses the year and month from the original date but always sets the day to 1.firstDay.AddMonths(1).AddDays(-1): Jumps to the first day of the following month, then steps back one day to land on the last day of the original month, regardless of whether it has 28, 29, 30, or 31 days.
Exercise 13: Calculate the Time Difference Between Two Dates
Practice Problem: Take two DateTime values (e.g., a project start and end time) and calculate the difference using TimeSpan. Display the result in total hours, total minutes, and total seconds.
Purpose: This exercise helps you practice subtracting two DateTime values into a TimeSpan, then reading its Total... properties, which express the whole duration in a single unit rather than broken into separate fields.
Given Input: projectStart = July 10, 2026 09:00:00, projectEnd = July 12, 2026 17:30:00
Expected Output:
Total Hours = 56.5 Total Minutes = 3390 Total Seconds = 203400
▼ Hint
- Subtracting one
DateTimefrom another withprojectEnd - projectStartproduces aTimeSpan. - Use
duration.TotalHours,duration.TotalMinutes, andduration.TotalSecondsto express the whole duration in each unit, rather thanduration.Hours, which would only give the leftover hours component.
▼ Solution & Explanation
Explanation:
projectEnd - projectStart: Subtracting twoDateTimevalues directly returns aTimeSpanrepresenting the elapsed duration between them.duration.TotalHours: Expresses the entire span as a single decimal number of hours, here 2 full days and 8.5 extra hours combined into 56.5.duration.TotalMinutesandduration.TotalSeconds: Convert the same overall duration into minutes and seconds respectively, rather than showing only the remainder within the next larger unit.
Exercise 14: Find All Fridays in a Month
Practice Problem: Write a program that finds and prints all the Fridays in a specific month and year provided by the user.
Purpose: This exercise helps you practice looping day by day through an entire month while checking the DayOfWeek property to collect every matching date.
Given Input: year = 2026, month = 7
Expected Output:
Fridays in 7/2026: 2026-07-03 2026-07-10 2026-07-17 2026-07-24 2026-07-31
▼ Hint
- Loop a
DateTimevariable from the first day of the month to the last day, incrementing by one day on each pass. - Inside the loop, check
day.DayOfWeek == DayOfWeek.Fridayand add matching dates to aList<DateTime>.
▼ Solution & Explanation
Explanation:
for (DateTime day = firstDay; day <= lastDay; day = day.AddDays(1)): Walks through every single date in the month, one day at a time, from the first day through the last day inclusive.day.DayOfWeek == DayOfWeek.Friday: Filters the loop down to only the dates that fall on a Friday.fridays.Add(day): Collects each matching date into a list so they can all be printed together after the loop finishes.
Exercise 15: Convert Between Local Time, UTC, and a Time Zone
Practice Problem: Take a local DateTime, convert it to Coordinated Universal Time (UTC), and then convert it back to a specific target time zone (e.g., “Eastern Standard Time”).
Purpose: This exercise helps you practice the standard round trip pattern for time zone conversion: local time to UTC with ToUniversalTime(), then UTC to any target zone with TimeZoneInfo.ConvertTimeFromUtc().
Given Input: localTime = July 13, 2026, 3:00 PM, marked as DateTimeKind.Local
Expected Output: A three line printout of the local time, the equivalent UTC time, and the equivalent Eastern time, where the UTC and Eastern values depend entirely on the machine’s configured local time zone.
Note: this exercise’s exact output cannot be pinned down in advance, since ToUniversalTime() uses whatever local time zone is configured on the machine running the code. It is also worth knowing that "Eastern Standard Time" is a Windows specific time zone ID, on Linux or macOS the IANA ID "America/New_York" should be used instead.
▼ Hint
- Call
.ToUniversalTime()directly on the localDateTimeto get its UTC equivalent. - Look up the target zone with
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"), then pass the UTC value intoTimeZoneInfo.ConvertTimeFromUtc()along with that zone.
▼ Solution & Explanation
Explanation:
localTime.ToUniversalTime(): Converts the local time to UTC based on the operating system’s configured time zone and offset, including daylight saving adjustments.TimeZoneInfo.FindSystemTimeZoneById(...): Looks up a specific named time zone from the operating system’s time zone database.TimeZoneInfo.ConvertTimeFromUtc(utcTime, easternZone): Converts a UTC value into the local time of the specified target zone, correctly applying that zone’s own daylight saving rules.
Exercise 16: Check if Two Date Ranges Overlap
Practice Problem: Write a function DoDatesOverlap(DateTime start1, DateTime end1, DateTime start2, DateTime end2) that returns true if two date ranges intersect.
Purpose: This exercise helps you practice the classic interval overlap check, useful for detecting scheduling conflicts, booking clashes, or overlapping subscription periods.
Given Input: Range 1 = July 1, 2026 to July 15, 2026, Range 2 = July 10, 2026 to July 20, 2026
Expected Output:
Range 1 = 2026-07-01 to 2026-07-15 Range 2 = 2026-07-10 to 2026-07-20 Do Dates Overlap = True
▼ Hint
Two ranges overlap exactly when the first range starts on or before the second range ends, and the second range starts on or before the first range ends: start1 <= end2 && start2 <= end1.
▼ Solution & Explanation
Explanation:
start1 <= end2 && start2 <= end1: This single condition captures every possible overlap case, including one range fully containing the other, without needing separate checks for each scenario.- Why it works: The two ranges fail to overlap only if one ends before the other begins, so negating that condition covers every case where they do intersect.
Exercise 17: Find the Start and End of a Day
Practice Problem: Given a DateTime representing an event notice (e.g., 2026-04-12 14:30:00), return two DateTime objects representing the absolute start of that day (00:00:00.000) and the absolute end of that day (23:59:59.999).
Purpose: This exercise helps you practice deriving day boundaries from any timestamp, a common requirement when filtering records that fall within a particular calendar day.
Given Input: eventNotice = April 12, 2026, 14:30:00
Expected Output:
Event Notice = 2026-04-12 14:30:00 Start of Day = 2026-04-12 00:00:00.000 End of Day = 2026-04-12 23:59:59.999
▼ Hint
- The
.Dateproperty strips off the time portion entirely, giving you midnight on the same calendar day for free. - For the end of day, take the start of the next day and subtract a single millisecond with
.AddDays(1).AddMilliseconds(-1).
▼ Solution & Explanation
Explanation:
eventNotice.Date: Returns a newDateTimewith the same year, month, and day, but with the time reset to midnight.eventNotice.Date.AddDays(1).AddMilliseconds(-1): Moves to midnight of the following day and then steps back exactly one millisecond, landing on the last possible instant of the original day.{startOfDay:yyyy-MM-dd HH:mm:ss.fff}: Thefffformat specifier includes the millisecond component so the precision of the boundary is visible in the output.
Exercise 18: Calculate an Invoice Due Date
Practice Problem: An invoice is generated today. It is due in 30 days. If the due date falls on a weekend, it rolls forward to the next Monday. Calculate the final due date.
Purpose: This exercise helps you practice applying a business rule on top of a simple date calculation, adjusting a raw result whenever it lands on a day that is not actually usable.
Given Input: invoiceDate = July 16, 2026 (a Thursday), due in 30 days
Expected Output:
Invoice Date = 2026-07-16 Due Date = 2026-08-17 (Monday)
▼ Hint
- Calculate the raw due date first with
invoiceDate.AddDays(30), before applying any weekend adjustment. - If the raw due date lands on a Saturday, push it forward by 2 days to reach Monday. If it lands on a Sunday, push it forward by just 1 day.
▼ Solution & Explanation
Explanation:
invoiceDate.AddDays(daysUntilDue): Computes the straightforward 30 day offset, landing on Saturday, August 15, 2026 before any weekend adjustment.if (dueDate.DayOfWeek == DayOfWeek.Saturday) dueDate = dueDate.AddDays(2);: Rolls a Saturday due date forward by two days to land on the following Monday.else if (dueDate.DayOfWeek == DayOfWeek.Sunday) dueDate = dueDate.AddDays(1);: Handles the Sunday case separately, since it only needs a single day shift to reach Monday.
Exercise 19: Find the Next Occurrence of a Weekday
Practice Problem: Write a method GetNextWeekday(DateTime start, DayOfWeek day) that finds the very next occurrence of a specific day (e.g., finding the next Tuesday).
Purpose: This exercise helps you practice a modulus based technique for finding the next matching weekday, a pattern useful for recurring reminders, weekly reports, or scheduled tasks.
Given Input: start = July 13, 2026 (a Monday), looking for the next Tuesday
Expected Output:
Start Date = 2026-07-13 (Monday) Next Tuesday = 2026-07-14 (Tuesday)
▼ Hint
DayOfWeekis really just an enum backed by integers from 0 (Sunday) through 6 (Saturday), so it can be cast tointfor arithmetic.- Compute
((int)day - (int)start.DayOfWeek + 7) % 7to get the number of days forward, then treat a result of exactly 0 as a full 7 days ahead, so the method always returns a date strictly afterstart.
▼ Solution & Explanation
Explanation:
((int)day - (int)start.DayOfWeek + 7) % 7: Calculates how many days ahead the target weekday falls, always producing a value between 0 and 6 regardless of which two days are being compared.daysToAdd == 0 ? 7 : daysToAdd: Handles the case wherestartalready falls on the target weekday, ensuring the method returns next week’s occurrence rather than the same day.start.AddDays(daysToAdd): Applies the calculated offset to land precisely on the next matching weekday.
Exercise 20: Use DateOnly and TimeOnly Instead of DateTime
Practice Problem: (.NET 6+) Rewrite a scenario where you only need a calendar date (like a birthday) and a clock time (like a daily alarm) using the modern DateOnly and TimeOnly structs instead of DateTime.
Purpose: This exercise helps you practice using DateOnly and TimeOnly for values that only ever need a date or only ever need a time, avoiding the unused, and sometimes misleading, extra component that a full DateTime would carry.
Given Input: birthday = September 5, 1998, dailyAlarm = 7:30 AM
Expected Output:
Birthday = 1998-09-05 Daily Alarm = 07:30
Note: DateOnly and TimeOnly require .NET 6 or later, they are not available in earlier .NET Framework or .NET Core versions.
▼ Hint
- Construct a birthday with
new DateOnly(1998, 9, 5), which stores only year, month, and day, with no time component at all. - Construct an alarm with
new TimeOnly(7, 30), which stores only hour and minute, with no date attached.
▼ Solution & Explanation
Explanation:
DateOnly birthday = new DateOnly(1998, 9, 5): Represents just a calendar date, with no possibility of an unintended time value like midnight sneaking into comparisons or storage.TimeOnly dailyAlarm = new TimeOnly(7, 30): Represents just a clock time, useful for recurring daily values that are not tied to any specific calendar date.- Clearer intent: Using these dedicated types instead of
DateTimemakes it obvious at a glance which part of a moment in time actually matters for that particular value.
Exercise 21: Measure Execution Time with a Stopwatch
Practice Problem: Measure how long a complex loop takes to execute using System.Diagnostics.Stopwatch, and format the elapsed time cleanly.
Purpose: This exercise helps you practice using Stopwatch to measure elapsed wall clock time around a block of code, which is far more precise than manually subtracting two DateTime.Now values.
Given Input: A loop that sums the numbers from 0 up to 9,999,999.
Expected Output:
Elapsed Time = 42.17 ms Elapsed Ticks = 421734
Note: since this measures actual wall clock time, the exact numbers will vary depending on your machine’s speed, current load, and whether the project is built in Debug or Release mode.
▼ Hint
- Call
Stopwatch.StartNew()to create and immediately start the timer, right before the code you want to measure. - Call
.Stop()right after the code finishes, then read.Elapsed.TotalMillisecondsfor a formatted duration or.ElapsedTicksfor the raw tick count.
▼ Solution & Explanation
Explanation:
Stopwatch.StartNew(): Creates a newStopwatchinstance and starts it in a single call, rather than requiring a separatenew Stopwatch()followed by.Start().stopwatch.Elapsed.TotalMilliseconds: Returns the elapsed duration as aTimeSpan, expressed here as a single decimal number of milliseconds.{...:F2}: Formats the millisecond value to exactly two decimal places for a clean, readable result.
Exercise 22: Find the Nth Weekday of a Month
Practice Problem: Write a function to find the N-th specific weekday of a month (e.g., calculate the date of the “2nd Tuesday of October 2026”).
Purpose: This exercise helps you practice combining the modulus based next-weekday technique with a simple week offset to reach any occurrence of a weekday within a month, not just the first one.
Given Input: year = 2026, month = 10, day = DayOfWeek.Tuesday, occurrence = 2
Expected Output: 2nd Tuesday of October 2026 = 2026-10-13 (Tuesday)
▼ Hint
- Find the first occurrence of the target weekday in the month using the same modulus technique as finding the next weekday, starting from the 1st of the month.
- Add
(occurrence - 1) * 7days to that first occurrence to jump forward to the requested week within the month.
▼ Solution & Explanation
Explanation:
((int)day - (int)firstDayOfMonth.DayOfWeek + 7) % 7: Calculates how many days after the 1st of the month the target weekday first appears, since October 1, 2026 falls on a Thursday, this lands on the 6th, the first Tuesday.firstMatch.AddDays((occurrence - 1) * 7): Jumps forward one full week for each additional occurrence requested, so occurrence 2 adds exactly 7 days to the first match.- Watch for month overflow: This simple implementation does not check whether the requested occurrence still falls within the same month, so requesting a 5th occurrence that does not exist would silently roll into the next month.
Exercise 23: Convert Between DateTime and a Unix Timestamp
Practice Problem: Convert a standard C# DateTime into a Unix timestamp (seconds elapsed since January 1, 1970) and vice versa.
Purpose: This exercise helps you practice using DateTimeOffset as a bridge for Unix timestamp conversion, which is the recommended approach since it explicitly tracks the UTC offset instead of relying on ambiguous local time assumptions.
Given Input: originalDate = July 13, 2026, 00:00:00 UTC
Expected Output:
Original Date (UTC) = 2026-07-13 00:00:00 Unix Timestamp = 1783900800 Converted Back = 2026-07-13 00:00:00
▼ Hint
- Wrap the UTC
DateTimein aDateTimeOffset, then call.ToUnixTimeSeconds()to get the timestamp. - To convert back, use the static method
DateTimeOffset.FromUnixTimeSeconds(timestamp), then read its.UtcDateTimeproperty to get a plainDateTimeagain.
▼ Solution & Explanation
Explanation:
new DateTimeOffset(dateTime.ToUniversalTime()): Wraps the UTC date in aDateTimeOffset, which pairs the date and time with an explicit zero offset from UTC..ToUnixTimeSeconds(): Calculates the number of whole seconds that have elapsed since the Unix epoch of January 1, 1970 00:00:00 UTC.DateTimeOffset.FromUnixTimeSeconds(unixTimestamp).UtcDateTime: Reverses the process, reconstructing aDateTimeOffsetfrom the raw timestamp and then extracting a plain UTCDateTimefrom it.
Exercise 24: Parse a Non-Standard Date Format Exactly
Practice Problem: Safely parse a highly non-standard date string like "25-2026-10 08:30 PM" into a valid DateTime object using DateTime.ParseExact().
Purpose: This exercise helps you practice using DateTime.ParseExact() with a custom format string for input that does not match any standard date layout DateTime.Parse() could guess on its own.
Given Input: rawDate = "25-2026-10 08:30 PM"
Expected Output: Parsed Date = 2026-10-25 20:30:00
▼ Hint
- Build a format string that mirrors the exact layout of the input, in this case
"dd-yyyy-MM hh:mm tt", matching day, then year, then month, then a 12-hour time with an AM/PM marker. - Pass
CultureInfo.InvariantCultureas the third argument so the parse does not depend on the current system culture’s date conventions.
▼ Solution & Explanation
Explanation:
"dd-yyyy-MM hh:mm tt": A custom format string where each token must line up exactly with the corresponding part of the input text, day first, then year, then month.DateTime.ParseExact(rawDate, format, CultureInfo.InvariantCulture): Parses the string using only the specified format, throwing aFormatExceptionimmediately if the input does not match it precisely.hh:mm tt: Matches a 12-hour clock time together with an AM or PM designator, whichParseExact()then converts internally into the correct 24-hour value.
Exercise 25: Detect Daylight Saving Time Gaps and Overlaps
Practice Problem: Write a program that detects if a given date and time in a specific time zone falls into an invalid “skipped” hour or an ambiguous “repeated” hour due to a Daylight Saving Time transition.
Purpose: This exercise helps you practice using TimeZoneInfo.IsInvalidTime() and TimeZoneInfo.IsAmbiguousTime() to catch the two edge cases that occur whenever clocks spring forward or fall back.
Given Input: skippedHourTime = March 8, 2026, 2:30 AM (during the spring forward transition), ambiguousHourTime = November 1, 2026, 1:30 AM (during the fall back transition), both checked against Eastern time.
Expected Output:
2026-03-08 02:30 is an invalid (skipped) time = True 2026-11-01 01:30 is an ambiguous (repeated) time = True
Note: "Eastern Standard Time" is the Windows specific time zone ID used here, on Linux or macOS the IANA ID "America/New_York" should be used instead. The exact transition dates also depend on the time zone’s current daylight saving rules, which are looked up from the operating system.
▼ Hint
- In the U.S., clocks spring forward at 2:00 AM on the second Sunday of March, meaning the local times from 2:00 AM up to 2:59 AM never actually occur that day.
- Clocks fall back at 2:00 AM on the first Sunday of November, meaning the local times from 1:00 AM up to 1:59 AM occur twice.
- Call
easternZone.IsInvalidTime(dateTime)for the skipped hour check, andeasternZone.IsAmbiguousTime(dateTime)for the repeated hour check.
▼ Solution & Explanation
Explanation:
easternZone.IsInvalidTime(skippedHourTime): Returns true when the given local time falls inside the hour that gets skipped entirely as clocks spring forward.easternZone.IsAmbiguousTime(ambiguousHourTime): Returns true when the given local time falls inside the hour that occurs twice as clocks fall back, since without an offset there is no way to tell which occurrence is meant.- Why this matters: Code that naively constructs local
DateTimevalues around these transition windows can silently represent a moment that either never happened or is genuinely ambiguous, which these two methods let you detect and handle explicitly.

Leave a Reply