Skip to content
Tutorials Center
My learning

Topics

Lesson 114 of 182 ยท Standard Library

Dates and Times

Learn C# dates and times - DateTime kinds, DateTimeOffset, TimeSpan, DateOnly, TimeOnly, formatting, parsing, time zones and TimeProvider for testable code.

Dates and times look simple until you ship them. A meeting "at 9:00" means something different in Berlin and in Lima, a clock jumps forward one hour in spring, a month has 28 to 31 days, and a DateTime that came out of a database may or may not know which time zone it belongs to. Most date bugs are not arithmetic mistakes; they come from picking the wrong type for the job.

.NET gives you five types that cover every case: DateTime, DateTimeOffset, TimeSpan, DateOnly and TimeOnly. This lesson shows what each one models, how to calculate with them, how to format and parse them safely, how time zones fit in, and how to write code that reads the clock in a way that tests can control.

Our editor runs on a server whose time zone is UTC and which uses invariant globalization. Local time therefore equals UTC here, and culture-specific names such as German month names are not available. On your own machine DateTime.Now will show your local time. Examples below avoid reading the real clock so the output is the same on every run.

Picking the right type

Type Models Example use
DateOnly A calendar date, no time Birthday, invoice date, holiday
TimeOnly A time of day, no date Opening hours, alarm at 07:30
DateTime A date and time, with a loose "kind" Local calculations, legacy code
DateTimeOffset A point in time plus its UTC offset Timestamps, logs, APIs
TimeSpan A length of time Timeouts, durations, differences

A good rule: if you mean "a moment that happened", store a DateTimeOffset (or a UTC DateTime). If you mean "a day on the calendar", use DateOnly. Reach for plain DateTime mainly when an API already hands you one.

Creating and calculating with DateTime

A DateTime is a count of ticks (100-nanosecond units) since 00:00:00 on January 1, year 1, plus a Kind flag. You can build one from its parts and read the parts back:

C# Building a DateTime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

DateTime is an immutable struct. Every Add... method returns a new value and leaves the original alone, so forgetting to use the result is a classic bug:

C# Add methods return new values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

AddMonths does not overflow into the next month: January 31 plus one month is February 28 in 2026, because February has no 31st. The compiler does not warn you here, so watch for statements that call an Add... method and discard the result.

Kind: Local, Utc, Unspecified

Every DateTime carries a Kind. It is a hint, not a time zone, and it is the root of many bugs:

  • DateTimeKind.Utc - the value is Coordinated Universal Time.
  • DateTimeKind.Local - the value is in the time zone of the machine running the code.
  • DateTimeKind.Unspecified - no idea. This is what you get from new DateTime(...) and from most database drivers.
C# DateTime.Kind

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In this sandbox local time is UTC, so converting changes nothing visible, but on a laptop in Tokyo utc.ToLocalTime() would show 21:00. Notice that plain == utc is true: equality looks only at ticks and ignores Kind. Two DateTime values in different zones can therefore compare equal or unequal for the wrong reason. That is the strongest argument for DateTimeOffset.

Do not call DateTime.Now in code that stores or compares timestamps. It depends on the machine's time zone and daylight-saving rules. Use DateTime.UtcNow or, better, DateTimeOffset.UtcNow, and convert to local time only when you display something to a person.

DateTimeOffset: a moment, unambiguously

A DateTimeOffset stores a date and time and the offset from UTC at that moment, for example +02:00. It identifies exactly one instant on the timeline, so comparing two of them is always correct, even when they were created in different zones:

C# DateTimeOffset

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Eighteen o'clock in Berlin in summer (UTC+2) and eleven o'clock in Lima (UTC-5) are the same instant, and == says so. The offset is not a time zone: it does not know when daylight saving starts. It only records what the offset was when the value was created, which is exactly what you want for a timestamp.

TimeSpan: durations

Subtracting two dates gives a TimeSpan. It is also what you use for timeouts and delays:

C# Working with TimeSpan

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Learn the difference between the properties without Total and those with it. Hours is the hours component (0 to 23), while TotalHours is the whole duration expressed in hours as a double. Mixing them up is a very common source of off-by-a-day reports.

A TimeSpan has no notion of months or years, because those have varying lengths. To count calendar months, work with DateOnly or compare year and month numbers yourself.

DateOnly and TimeOnly

Since .NET 6 you can say exactly what you mean. A birthday is a date, not a moment, so it should not carry a time or a zone:

C# DateOnly and TimeOnly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

TimeOnly wraps around midnight: new TimeOnly(23, 0).AddHours(2) is 01:00. Subtracting two TimeOnly values gives a TimeSpan, and IsBetween handles ranges that cross midnight correctly (for example a night shift from 22:00 to 06:00).

Formatting dates

ToString accepts a standard format (one letter) or a custom format (a pattern):

C# Date format strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The pattern letters worth memorizing: yyyy year, MM month number, MMM/MMMM month name, dd day, ddd/dddd weekday name, HH hour 00-23, hh hour 01-12, mm minutes, ss seconds, fff milliseconds, tt AM/PM, zzz UTC offset. Case matters: MM is month and mm is minutes, which is the number one formatting typo.

For anything that leaves your program (files, APIs, databases) use the invariant, sortable forms: "o" for a round-trippable ISO 8601 string, or the default DateTimeOffset formatting. Display formats such as "D" depend on the viewer's culture.

Parsing dates

Parse with TryParse when the text comes from a user or a file, and ParseExact when you know the precise layout:

C# Parsing dates safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Always pass CultureInfo.InvariantCulture (or a specific culture) when parsing text that isn't meant for the current user. Without it, "03/04/2026" is March 4 on one machine and April 3 on another.

Time zones with TimeZoneInfo

TimeZoneInfo knows named zones with their daylight-saving rules. On Windows the ids look like "W. Europe Standard Time", on Linux and macOS like "Europe/Berlin"; since .NET 6 either form works on both systems if the zone data is present:

C#
// Read-only: needs time zone data, which our sandbox does not ship.
var berlin = TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin");
var utcNow = DateTimeOffset.UtcNow;
var inBerlin = TimeZoneInfo.ConvertTime(utcNow, berlin);
Console.WriteLine(inBerlin);
Console.WriteLine(berlin.IsDaylightSavingTime(inBerlin));

The sandbox has only UTC, so here is what we can run: the built-in zones and a custom fixed-offset zone.

C# TimeZoneInfo basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The practical advice: store instants in UTC, store the user's zone id as text next to them if you need to show local times, and convert at the edges. Never add TimeSpan.FromHours(offset) by hand for a named zone: daylight saving makes the offset change during the year.

Invalid and ambiguous local times

Twice a year, local clocks skip an hour (spring) or repeat one (autumn). Local times inside those hours are invalid or ambiguous. TimeZoneInfo.IsInvalidTime and IsAmbiguousTime detect them. This is another reason to keep storage in UTC: UTC never skips or repeats.

TimeProvider: testable clocks

Code that calls DateTime.UtcNow directly is hard to test, because the result changes every run. .NET 8 added the abstract class TimeProvider. You take one as a dependency, call GetUtcNow() on it, and in production pass TimeProvider.System. In tests you pass a fake you control. The fake from Microsoft.Extensions.TimeProvider.Testing is a NuGet package, so here is the same idea with a tiny hand-written subclass:

C# A testable clock with TimeProvider

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

TimeProvider also creates timers and measures elapsed time, so code that waits can be driven by a fake as well. Use it in any new code whose behavior depends on "now", and register TimeProvider.System in dependency injection (see Dependency Injection).

A tour of useful DateTime and TimeSpan members

The sections above covered the big ideas. These smaller members answer everyday questions and show up in older code:

  • Subtract is the method form of the - operator; end.Subtract(start) gives a TimeSpan.
  • TimeSpan.FromDays, FromHours and FromMinutes build durations (fractions allowed); Days, Hours are the parts, while TotalHours is the whole duration in hours.
  • ToString("D") or ToLongDateString() give a long date, and custom formats such as "dddd, d MMMM yyyy" give full control.
  • ToBinary and ToFileTimeUtc (with FromBinary, FromFileTimeUtc) convert to a number and back. They are used for compact storage and for Windows file timestamps; for new data prefer ISO 8601 text or DateTimeOffset.
  • DateTime.SpecifyKind labels a value with a Kind without changing its clock reading, which is the fix when a value read from a database comes back Unspecified.
  • IsLeapYear, DaysInMonth, DayOfYear and DayOfWeek cover calendar questions.
C# DateTime and TimeSpan tour

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The gap prints as 3.08:15:30, which is the TimeSpan default format days.hours:minutes:seconds. TotalHours is 80.26 because three days plus eight hours is 80 hours and a quarter. SpecifyKind changed only the label: Unspecified became Utc and the clock reading stayed 12:00.

Common mistakes

  • Using DateTime.Now for stored timestamps. Use UTC.
  • Comparing DateTime values of different kinds and trusting the result.
  • Formatting with mm when you meant MM.
  • Parsing user text without a culture or without TryParse.
  • Using TotalDays where you need the whole-days Days, or the other way round.
  • Representing a calendar date as a DateTime at midnight; time zone conversions then shift it to the previous or next day. Use DateOnly.
  • Measuring performance with DateTime. Its resolution is coarse; use Stopwatch or TimeProvider.GetTimestamp().

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which type is the best fit for a customer's birthday?

    A birthday is a calendar date with no time of day and no time zone. DateOnly says exactly that and avoids midnight-shift bugs.
  2. 2. What does new DateTime(2026, 1, 31).AddMonths(1) produce?

    AddMonths clamps to the last valid day of the target month, so the result is February 28, 2026.
  3. 3. Why is DateTimeOffset safer than DateTime for timestamps?

    DateTimeOffset stores the offset from UTC along with the date and time. It does not store a named zone, but it does pin down a single instant.
  4. 4. In a custom format string, what does "mm" mean?

    Lowercase mm is minutes and uppercase MM is the month number. Mixing them up is a classic typo.
  5. 5. How do you make code that reads the current time testable?

    TimeProvider is an abstraction over the clock. Production code uses TimeProvider.System, tests use a fake with a controllable time.

Summary

  • DateTime is a tick count with a Kind flag; its comparisons ignore the kind. Add... methods return new values.
  • DateTimeOffset identifies an exact instant and is the best default for timestamps. Store and compare in UTC.
  • TimeSpan is a duration; Hours is a component, TotalHours the whole length.
  • DateOnly and TimeOnly model dates and times of day without a zone.
  • Format with ToString patterns (yyyy-MM-dd, "o" for round trips) and parse with TryParse/ParseExact and an explicit culture.
  • TimeZoneInfo handles named zones and daylight saving; the sandbox has UTC only.
  • Inject a TimeProvider so tests can control the clock.

Next: Math, BigInteger and Random