PYnative

Python Programming

  • Learn Python ▼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises ▼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • Quizzes
  • Code Editor ▼
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » C# Exercises » C# DateTime Exercises: 25 Coding Problems with Solutions

C# DateTime Exercises: 25 Coding Problems with Solutions

Updated on: July 15, 2026 | Leave a Comment

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 DateTime format strings.
  • Parsing: DateTime.Parse() and DateTime.TryParse().
  • Arithmetic: .AddDays(), .AddMonths(), and TimeSpan differences.
  • 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.Now to get the current date and time together, including hours, minutes, and seconds.
  • Use DateTime.Today to get just the date portion, with the time always set to midnight.
  • Read the DayOfWeek property off either value to get the current day as an enum, which prints as its name automatically.
▼ Solution & Explanation
using System;

namespace DateTimeExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime now = DateTime.Now;
            DateTime today = DateTime.Today;
            DayOfWeek dayOfWeek = now.DayOfWeek;

            Console.WriteLine($"Current Date and Time = {now}");
            Console.WriteLine($"Current Date Only = {today:yyyy-MM-dd}");
            Console.WriteLine($"Current Day of Week = {dayOfWeek}");
        }
    }
}Code language: C# (cs)

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 a DayOfWeek enum 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}.
  • dddd and MMMM print the full day and month names, while lowercase dd and uppercase MM print zero-padded numeric values.
▼ Solution & Explanation
using System;

namespace DateTimeExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime date = new DateTime(2026, 10, 25);

            Console.WriteLine($"MM/dd/yyyy = {date:MM/dd/yyyy}");
            Console.WriteLine($"Full Format = {date:dddd, dd MMMM yyyy}");
            Console.WriteLine($"ISO 8601 = {date:yyyy-MM-dd HH:mm:ss}");
        }
    }
}Code language: C# (cs)

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
using System;

namespace DateTimeExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime moment = new DateTime(2026, 3, 15, 14, 30, 45, 250);

            Console.WriteLine($"Year = {moment.Year}");
            Console.WriteLine($"Month = {moment.Month}");
            Console.WriteLine($"Day = {moment.Day}");
            Console.WriteLine($"Hour = {moment.Hour}");
            Console.WriteLine($"Minute = {moment.Minute}");
            Console.WriteLine($"Second = {moment.Second}");
            Console.WriteLine($"Millisecond = {moment.Millisecond}");
        }
    }
}Code language: C# (cs)

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 DayOfYear property 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
using System;

namespace DateTimeExercises
{
    class Program
    {
        static int GetDayOfYear(DateTime date)
        {
            return date.DayOfYear;
        }

        static void Main(string[] args)
        {
            DateTime date = new DateTime(2026, 12, 31);
            int dayNumber = GetDayOfYear(date);

            Console.WriteLine($"Date = {date:yyyy-MM-dd}");
            Console.WriteLine($"Day of Year = {dayNumber}");
        }
    }
}Code language: C# (cs)

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 a DateTime directly, but throws FormatException if 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
using System;

namespace DateTimeExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            string dateText = "2026-12-25";

            DateTime parsedDate = DateTime.Parse(dateText);
            Console.WriteLine($"Parsed with Parse() = {parsedDate:yyyy-MM-dd}");

            bool success = DateTime.TryParse(dateText, out DateTime safeParsedDate);
            Console.WriteLine($"TryParse Succeeded = {success}");
            Console.WriteLine($"Parsed with TryParse() = {safeParsedDate:yyyy-MM-dd}");
        }
    }
}Code language: C# (cs)

Explanation:

  • DateTime.Parse(dateText): Converts the string directly into a DateTime, but would throw a FormatException if the text were not a recognizable date.
  • DateTime.TryParse(dateText, out DateTime safeParsedDate): Attempts the same conversion but returns false instead 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 DateTime values produces a TimeSpan, whose .Days property gives the whole number of days between them.
▼ Solution & Explanation
using System;

namespace DateTimeExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime today = DateTime.Today;
            DateTime christmas = new DateTime(today.Year, 12, 25);

            if (christmas < today)
            {
                christmas = christmas.AddYears(1);
            }

            int daysUntilChristmas = (christmas - today).Days;

            Console.WriteLine($"Today = {today:yyyy-MM-dd}");
            Console.WriteLine($"Next Christmas = {christmas:yyyy-MM-dd}");
            Console.WriteLine($"Days Until Christmas = {daysUntilChristmas}");
        }
    }
}Code language: C# (cs)

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 a TimeSpan, and its Days property 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
using System;

namespace DateTimeExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime today = DateTime.Today;
            DateTime yesterday = today.AddDays(-1);
            DateTime tomorrow = today.AddDays(1);

            Console.WriteLine($"Yesterday = {yesterday:yyyy-MM-dd}");
            Console.WriteLine($"Today = {today:yyyy-MM-dd}");
            Console.WriteLine($"Tomorrow = {tomorrow:yyyy-MM-dd}");
        }
    }
}Code language: C# (cs)

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 new DateTime rather than modifying today itself, since DateTime values 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.Year as an initial estimate of the age.
  • Compare birthDate.Date to today.AddYears(-age), and subtract one from the age if the birthday has not yet occurred this year.
▼ Solution & Explanation
using System;

namespace DateTimeExercises
{
    class Program
    {
        static int CalculateAge(DateTime birthDate)
        {
            DateTime today = DateTime.Today;
            int age = today.Year - birthDate.Year;

            if (birthDate.Date > today.AddYears(-age))
            {
                age--;
            }

            return age;
        }

        static void Main(string[] args)
        {
            DateTime birthDate = new DateTime(1998, 9, 5);
            int age = CalculateAge(birthDate);

            Console.WriteLine($"Birth Date = {birthDate:yyyy-MM-dd}");
            Console.WriteLine($"Age = {age}");
        }
    }
}Code language: C# (cs)

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-else chain on the comparison result to print the appropriate message.
▼ Solution & Explanation
using System;

namespace DateTimeExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime firstDate = new DateTime(2026, 5, 10);
            DateTime secondDate = new DateTime(2026, 8, 22);

            int comparison = DateTime.Compare(firstDate, secondDate);

            if (comparison < 0)
            {
                Console.WriteLine($"{firstDate:yyyy-MM-dd} comes before {secondDate:yyyy-MM-dd}");
            }
            else if (comparison > 0)
            {
                Console.WriteLine($"{firstDate:yyyy-MM-dd} comes after {secondDate:yyyy-MM-dd}");
            }
            else
            {
                Console.WriteLine("Both dates are identical.");
            }
        }
    }
}Code language: C# (cs)

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 that firstDate occurs chronologically before secondDate.
  • Alternative: The comparison operators <, >, and == work directly on DateTime values too, and would produce the same result as DateTime.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
using System;

namespace DateTimeExercises
{
    class Program
    {
        static DateTime AddBusinessDays(DateTime start, int days)
        {
            DateTime result = start;
            int addedDays = 0;

            while (addedDays < days)
            {
                result = result.AddDays(1);

                if (result.DayOfWeek != DayOfWeek.Saturday && result.DayOfWeek != DayOfWeek.Sunday)
                {
                    addedDays++;
                }
            }

            return result;
        }

        static void Main(string[] args)
        {
            DateTime startDate = new DateTime(2026, 7, 10);
            int businessDaysToAdd = 5;

            DateTime resultDate = AddBusinessDays(startDate, businessDaysToAdd);

            Console.WriteLine($"Start Date = {startDate:yyyy-MM-dd} ({startDate.DayOfWeek})");
            Console.WriteLine($"Result Date = {resultDate:yyyy-MM-dd} ({resultDate.DayOfWeek})");
        }
    }
}Code language: C# (cs)

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 days total.

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
using System;

namespace DateTimeExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime date = new DateTime(2028, 6, 1);
            bool isLeapYear = DateTime.IsLeapYear(date.Year);

            Console.WriteLine($"Year = {date.Year}");
            Console.WriteLine($"Is Leap Year = {isLeapYear}");
        }
    }
}Code language: C# (cs)

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
using System;

namespace DateTimeExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime date = new DateTime(2026, 2, 17);

            DateTime firstDay = new DateTime(date.Year, date.Month, 1);
            DateTime lastDay = firstDay.AddMonths(1).AddDays(-1);

            Console.WriteLine($"Given Date = {date:yyyy-MM-dd}");
            Console.WriteLine($"First Day of Month = {firstDay:yyyy-MM-dd}");
            Console.WriteLine($"Last Day of Month = {lastDay:yyyy-MM-dd}");
        }
    }
}Code language: C# (cs)

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 DateTime from another with projectEnd - projectStart produces a TimeSpan.
  • Use duration.TotalHours, duration.TotalMinutes, and duration.TotalSeconds to express the whole duration in each unit, rather than duration.Hours, which would only give the leftover hours component.
▼ Solution & Explanation
using System;

namespace DateTimeExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime projectStart = new DateTime(2026, 7, 10, 9, 0, 0);
            DateTime projectEnd = new DateTime(2026, 7, 12, 17, 30, 0);

            TimeSpan duration = projectEnd - projectStart;

            Console.WriteLine($"Total Hours = {duration.TotalHours}");
            Console.WriteLine($"Total Minutes = {duration.TotalMinutes}");
            Console.WriteLine($"Total Seconds = {duration.TotalSeconds}");
        }
    }
}Code language: C# (cs)

Explanation:

  • projectEnd - projectStart: Subtracting two DateTime values directly returns a TimeSpan representing 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.TotalMinutes and duration.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 DateTime variable 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.Friday and add matching dates to a List<DateTime>.
▼ Solution & Explanation
using System;
using System.Collections.Generic;

namespace DateTimeExercises
{
    class Program
    {
        static List<DateTime> FindAllFridays(int year, int month)
        {
            List<DateTime> fridays = new List<DateTime>();
            DateTime firstDay = new DateTime(year, month, 1);
            DateTime lastDay = firstDay.AddMonths(1).AddDays(-1);

            for (DateTime day = firstDay; day <= lastDay; day = day.AddDays(1))
            {
                if (day.DayOfWeek == DayOfWeek.Friday)
                {
                    fridays.Add(day);
                }
            }

            return fridays;
        }

        static void Main(string[] args)
        {
            int year = 2026;
            int month = 7;

            List<DateTime> fridays = FindAllFridays(year, month);

            Console.WriteLine($"Fridays in {month}/{year}:");
            foreach (DateTime friday in fridays)
            {
                Console.WriteLine(friday.ToString("yyyy-MM-dd"));
            }
        }
    }
}Code language: C# (cs)

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 local DateTime to get its UTC equivalent.
  • Look up the target zone with TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"), then pass the UTC value into TimeZoneInfo.ConvertTimeFromUtc() along with that zone.
▼ Solution & Explanation
using System;

namespace DateTimeExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime localTime = new DateTime(2026, 7, 13, 15, 0, 0, DateTimeKind.Local);
            DateTime utcTime = localTime.ToUniversalTime();

            TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
            DateTime easternTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, easternZone);

            Console.WriteLine($"Local Time = {localTime:yyyy-MM-dd HH:mm:ss}");
            Console.WriteLine($"UTC Time = {utcTime:yyyy-MM-dd HH:mm:ss}");
            Console.WriteLine($"Eastern Time = {easternTime:yyyy-MM-dd HH:mm:ss}");
        }
    }
}Code language: C# (cs)

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
using System;

namespace DateTimeExercises
{
    class Program
    {
        static bool DoDatesOverlap(DateTime start1, DateTime end1, DateTime start2, DateTime end2)
        {
            return start1 <= end2 && start2 <= end1;
        }

        static void Main(string[] args)
        {
            DateTime start1 = new DateTime(2026, 7, 1);
            DateTime end1 = new DateTime(2026, 7, 15);
            DateTime start2 = new DateTime(2026, 7, 10);
            DateTime end2 = new DateTime(2026, 7, 20);

            bool overlaps = DoDatesOverlap(start1, end1, start2, end2);

            Console.WriteLine($"Range 1 = {start1:yyyy-MM-dd} to {end1:yyyy-MM-dd}");
            Console.WriteLine($"Range 2 = {start2:yyyy-MM-dd} to {end2:yyyy-MM-dd}");
            Console.WriteLine($"Do Dates Overlap = {overlaps}");
        }
    }
}Code language: C# (cs)

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 .Date property 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
using System;

namespace DateTimeExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime eventNotice = new DateTime(2026, 4, 12, 14, 30, 0);

            DateTime startOfDay = eventNotice.Date;
            DateTime endOfDay = eventNotice.Date.AddDays(1).AddMilliseconds(-1);

            Console.WriteLine($"Event Notice = {eventNotice:yyyy-MM-dd HH:mm:ss}");
            Console.WriteLine($"Start of Day = {startOfDay:yyyy-MM-dd HH:mm:ss.fff}");
            Console.WriteLine($"End of Day = {endOfDay:yyyy-MM-dd HH:mm:ss.fff}");
        }
    }
}Code language: C# (cs)

Explanation:

  • eventNotice.Date: Returns a new DateTime with 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}: The fff format 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
using System;

namespace DateTimeExercises
{
    class Program
    {
        static DateTime CalculateDueDate(DateTime invoiceDate, int daysUntilDue)
        {
            DateTime dueDate = invoiceDate.AddDays(daysUntilDue);

            if (dueDate.DayOfWeek == DayOfWeek.Saturday)
            {
                dueDate = dueDate.AddDays(2);
            }
            else if (dueDate.DayOfWeek == DayOfWeek.Sunday)
            {
                dueDate = dueDate.AddDays(1);
            }

            return dueDate;
        }

        static void Main(string[] args)
        {
            DateTime invoiceDate = new DateTime(2026, 7, 16);
            DateTime dueDate = CalculateDueDate(invoiceDate, 30);

            Console.WriteLine($"Invoice Date = {invoiceDate:yyyy-MM-dd}");
            Console.WriteLine($"Due Date = {dueDate:yyyy-MM-dd} ({dueDate.DayOfWeek})");
        }
    }
}Code language: C# (cs)

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
  • DayOfWeek is really just an enum backed by integers from 0 (Sunday) through 6 (Saturday), so it can be cast to int for arithmetic.
  • Compute ((int)day - (int)start.DayOfWeek + 7) % 7 to 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 after start.
▼ Solution & Explanation
using System;

namespace DateTimeExercises
{
    class Program
    {
        static DateTime GetNextWeekday(DateTime start, DayOfWeek day)
        {
            int daysToAdd = ((int)day - (int)start.DayOfWeek + 7) % 7;
            daysToAdd = daysToAdd == 0 ? 7 : daysToAdd;

            return start.AddDays(daysToAdd);
        }

        static void Main(string[] args)
        {
            DateTime start = new DateTime(2026, 7, 13);
            DateTime nextTuesday = GetNextWeekday(start, DayOfWeek.Tuesday);

            Console.WriteLine($"Start Date = {start:yyyy-MM-dd} ({start.DayOfWeek})");
            Console.WriteLine($"Next Tuesday = {nextTuesday:yyyy-MM-dd} ({nextTuesday.DayOfWeek})");
        }
    }
}Code language: C# (cs)

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 where start already 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
using System;

namespace DateTimeExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            DateOnly birthday = new DateOnly(1998, 9, 5);
            TimeOnly dailyAlarm = new TimeOnly(7, 30);

            Console.WriteLine($"Birthday = {birthday:yyyy-MM-dd}");
            Console.WriteLine($"Daily Alarm = {dailyAlarm:HH:mm}");
        }
    }
}Code language: C# (cs)

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 DateTime makes 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.TotalMilliseconds for a formatted duration or .ElapsedTicks for the raw tick count.
▼ Solution & Explanation
using System;
using System.Diagnostics;

namespace DateTimeExercises
{
    class Program
    {
        static void RunComplexLoop()
        {
            long total = 0;
            for (int i = 0; i < 10000000; i++)
            {
                total += i;
            }
        }

        static void Main(string[] args)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            RunComplexLoop();
            stopwatch.Stop();

            Console.WriteLine($"Elapsed Time = {stopwatch.Elapsed.TotalMilliseconds:F2} ms");
            Console.WriteLine($"Elapsed Ticks = {stopwatch.ElapsedTicks}");
        }
    }
}Code language: C# (cs)

Explanation:

  • Stopwatch.StartNew(): Creates a new Stopwatch instance and starts it in a single call, rather than requiring a separate new Stopwatch() followed by .Start().
  • stopwatch.Elapsed.TotalMilliseconds: Returns the elapsed duration as a TimeSpan, 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) * 7 days to that first occurrence to jump forward to the requested week within the month.
▼ Solution & Explanation
using System;

namespace DateTimeExercises
{
    class Program
    {
        static DateTime GetNthWeekdayOfMonth(int year, int month, DayOfWeek day, int occurrence)
        {
            DateTime firstDayOfMonth = new DateTime(year, month, 1);
            int daysUntilFirstMatch = ((int)day - (int)firstDayOfMonth.DayOfWeek + 7) % 7;
            DateTime firstMatch = firstDayOfMonth.AddDays(daysUntilFirstMatch);

            return firstMatch.AddDays((occurrence - 1) * 7);
        }

        static void Main(string[] args)
        {
            DateTime secondTuesday = GetNthWeekdayOfMonth(2026, 10, DayOfWeek.Tuesday, 2);

            Console.WriteLine($"2nd Tuesday of October 2026 = {secondTuesday:yyyy-MM-dd} ({secondTuesday.DayOfWeek})");
        }
    }
}Code language: C# (cs)

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 DateTime in a DateTimeOffset, then call .ToUnixTimeSeconds() to get the timestamp.
  • To convert back, use the static method DateTimeOffset.FromUnixTimeSeconds(timestamp), then read its .UtcDateTime property to get a plain DateTime again.
▼ Solution & Explanation
using System;

namespace DateTimeExercises
{
    class Program
    {
        static long ToUnixTimestamp(DateTime dateTime)
        {
            DateTimeOffset dateTimeOffset = new DateTimeOffset(dateTime.ToUniversalTime());
            return dateTimeOffset.ToUnixTimeSeconds();
        }

        static DateTime FromUnixTimestamp(long unixTimestamp)
        {
            return DateTimeOffset.FromUnixTimeSeconds(unixTimestamp).UtcDateTime;
        }

        static void Main(string[] args)
        {
            DateTime originalDate = new DateTime(2026, 7, 13, 0, 0, 0, DateTimeKind.Utc);

            long unixTimestamp = ToUnixTimestamp(originalDate);
            DateTime convertedBack = FromUnixTimestamp(unixTimestamp);

            Console.WriteLine($"Original Date (UTC) = {originalDate:yyyy-MM-dd HH:mm:ss}");
            Console.WriteLine($"Unix Timestamp = {unixTimestamp}");
            Console.WriteLine($"Converted Back = {convertedBack:yyyy-MM-dd HH:mm:ss}");
        }
    }
}Code language: C# (cs)

Explanation:

  • new DateTimeOffset(dateTime.ToUniversalTime()): Wraps the UTC date in a DateTimeOffset, 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 a DateTimeOffset from the raw timestamp and then extracting a plain UTC DateTime from 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.InvariantCulture as the third argument so the parse does not depend on the current system culture’s date conventions.
▼ Solution & Explanation
using System;
using System.Globalization;

namespace DateTimeExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            string rawDate = "25-2026-10 08:30 PM";
            string format = "dd-yyyy-MM hh:mm tt";

            DateTime parsedDate = DateTime.ParseExact(rawDate, format, CultureInfo.InvariantCulture);

            Console.WriteLine($"Raw Text = {rawDate}");
            Console.WriteLine($"Parsed Date = {parsedDate:yyyy-MM-dd HH:mm:ss}");
        }
    }
}Code language: C# (cs)

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 a FormatException immediately if the input does not match it precisely.
  • hh:mm tt: Matches a 12-hour clock time together with an AM or PM designator, which ParseExact() 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, and easternZone.IsAmbiguousTime(dateTime) for the repeated hour check.
▼ Solution & Explanation
using System;

namespace DateTimeExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");

            DateTime skippedHourTime = new DateTime(2026, 3, 8, 2, 30, 0);
            DateTime ambiguousHourTime = new DateTime(2026, 11, 1, 1, 30, 0);

            bool isInvalid = easternZone.IsInvalidTime(skippedHourTime);
            bool isAmbiguous = easternZone.IsAmbiguousTime(ambiguousHourTime);

            Console.WriteLine($"{skippedHourTime:yyyy-MM-dd HH:mm} is an invalid (skipped) time = {isInvalid}");
            Console.WriteLine($"{ambiguousHourTime:yyyy-MM-dd HH:mm} is an ambiguous (repeated) time = {isAmbiguous}");
        }
    }
}Code language: C# (cs)

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 DateTime values 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.

Filed Under: C# Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

C# Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: C# Exercises
TweetF  sharein  shareP  Pin

  C# Exercises

  • C# Exercise for Beginners
  • C# Loops Exercise
  • C# Array Exercise
  • C# String Exercise
  • C# OOP Exercise
  • C# Structs, Records and Enums Exercise
  • C# Collections Exercise
  • C# List Exercise
  • C# Dictionary Exercise
  • C# LINQ Exercise
  • C# Exception Handling Exercise
  • C# File Handling Exercise
  • C# Date and Time Exercise
  • C# Generics Exercise
  • C# Lambda Expressions Exercise
  • C# Delegates and Events Exercise
  • C# Extension Methods Exercise
  • C# Regex Exercise
  • C# Pattern Matching Exercise
  • C# Iterators and Yield Exercise
  • C# Indexers and Operator Overloading Exercise
  • C# Random Data Generation Exercise

All Coding Exercises

Python Exercises C Exercises C++ Exercises Java Exercises C# Exercises

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com