Working with Dates and Time in C#: A Complete Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to Working with Dates and Time in C#



Working with dates and time is one of the fundamental tasks in software development. Whether it's event logging, deadline calculations, report generation, or working with databases — the ability to properly manage temporal data is critically important. In C# (.NET platform), there is a powerful and flexible set of tools for these purposes, including the DateTime, TimeSpan, and DateTimeOffset structures.



In this article, we will thoroughly examine all key aspects of working with dates and time in C#. You will learn how to create, format, compare, and manipulate temporal data, and also get acquainted with best practices that will help you avoid common mistakes.



Core Structures: DateTime, TimeSpan, and DateTimeOffset



DateTime Structure



DateTime is the primary structure for representing a point in time (date + time). It can represent values from 01.01.0001 to 31.12.9999.



Creating a DateTime object:



// Current date and timeDateTime now = DateTime.Now;DateTime utcNow = DateTime.UtcNow;

// Specific date and timeDateTime specificDate = new DateTime(2025, 3, 15, 14, 30, 0); // March 15, 2025, 14:30:00

// Parsing from a stringDateTime parsedDate = DateTime.Parse("2025-03-15");

// Using TryParse for safe parsingif (DateTime.TryParse("2025-03-15", out DateTime result)){ Console.WriteLine($"Successfully parsed: {result}");}


Key properties and methods:



  • Date — returns only the date (time = 00:00:00)
  • Year, Month, Day, Hour, Minute, Second — individual components
  • DayOfWeek — day of the week (enum)
  • AddDays(), AddMonths(), AddYears() — date arithmetic
  • AddHours(), AddMinutes(), AddSeconds() — time arithmetic


TimeSpan Structure



TimeSpan represents a time interval (the gap between two moments). It is not a date, but specifically a duration.



// Creating a TimeSpanTimeSpan interval = new TimeSpan(2, 15, 30); // 2 hours, 15 minutes, 30 seconds

// Difference between two datesDateTime start = new DateTime(2025, 1, 1);DateTime end = new DateTime(2025, 1, 10);TimeSpan difference = end - start; // 9 days

// TimeSpan propertiesConsole.WriteLine($"Days: {difference.Days}"); // 9Console.WriteLine($"Total hours: {difference.TotalHours}"); // 216Console.WriteLine($"Total minutes: {difference.TotalMinutes}"); // 12960

// Arithmetic with TimeSpanTimeSpan workDay = new TimeSpan(8, 0, 0); // 8 hoursTimeSpan breakTime = new TimeSpan(1, 0, 0); // 1 hourTimeSpan actualWork = workDay - breakTime; // 7 hours


DateTimeOffset Structure



DateTimeOffset is an enhanced version of DateTime that takes into account the offset relative to UTC. This is critically important for applications working with users from different time zones.



// Current time considering time zoneDateTimeOffset nowOffset = DateTimeOffset.Now;

// Creating with a specified offsetDateTimeOffset withOffset = new DateTimeOffset(2025, 3, 15, 14, 0, 0, TimeSpan.FromHours(3));

// Conversion between time zonesDateTimeOffset utc = withOffset.ToUniversalTime();DateTimeOffset local = withOffset.ToLocalTime();

// Getting the offsetConsole.WriteLine($"Offset: {withOffset.Offset}"); // +03:00


When to use DateTimeOffset instead of DateTime? If your application works with users from different time zones or stores data in UTC, use DateTimeOffset. This prevents

Blogs

Book Recommendations