跳到主要内容

DateTime and TimeSpan

Short, interview-ready summary of date/time in C#.


"DateTime = point in time; TimeSpan = duration; DateTimeOffset = point in time + offset"


DateTime

var now = DateTime.Now; // local
var utc = DateTime.UtcNow; // UTC (prefer for storage/APIs)
var today = DateTime.Today; // date only, time 00:00:00

var d = new DateTime(2025, 1, 15);
var d2 = new DateTime(2025, 1, 15, 14, 30, 0);

Properties

int year = now.Year;
int month = now.Month;
int day = now.Day;
int hour = now.Hour;
DayOfWeek dow = now.DayOfWeek;

Formatting

string s = now.ToString("yyyy-MM-dd");           // 2025-01-15
string s2 = now.ToString("yyyy-MM-dd HH:mm:ss"); // 2025-01-15 14:30:00
string s3 = now.ToString("o"); // round-trip (ISO 8601)

Parsing

DateTime d = DateTime.Parse("2025-01-15");
if (DateTime.TryParse("2025-01-15", out DateTime result)) { }
DateTime d2 = DateTime.ParseExact("15/01/2025", "dd/MM/yyyy", CultureInfo.InvariantCulture);

TimeSpan (duration)

var ts = TimeSpan.FromHours(2);
var ts2 = TimeSpan.FromMinutes(90);
var ts3 = new TimeSpan(1, 30, 0); // days, hours, minutes (or add seconds)

var diff = end - start; // DateTime subtraction → TimeSpan

Properties

double totalHours = ts.TotalHours;
int hours = ts.Hours;
int minutes = ts.Minutes;

DateTimeOffset (time + offset)

"Use when you need time zone / offset info"

var dto = DateTimeOffset.UtcNow;
var dto2 = new DateTimeOffset(2025, 1, 15, 14, 30, 0, TimeSpan.FromHours(8));
TimeSpan offset = dto.Offset;
DateTime utc = dto.UtcDateTime;
  • Prefer DateTimeOffset for APIs and storage when time zone matters
  • DateTime has a Kind (Utc, Local, Unspecified) but no offset

Common operations

var tomorrow = now.AddDays(1);
var nextWeek = now.AddDays(7);
var diff = end - start; // TimeSpan
bool isBefore = d1 < d2;

Time zones

TimeZoneInfo tz = TimeZoneInfo.Local;
TimeZoneInfo.ConvertTimeFromUtc(utc, tz);
TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
  • DateTime does not store time zone; DateTimeOffset stores offset
  • For full time zone (DST, rules), use TimeZoneInfo

Interview one-liner

"DateTime is a point in time; TimeSpan is a duration. Prefer UtcNow for storage and APIs; use DateTimeOffset when you need offset. Format with ToString patterns or ISO 8601; parse with TryParse or ParseExact with culture."


Cheat sheet

DateTime.Now = local; UtcNow = UTC (prefer)
TimeSpan = duration; end - start
DateTimeOffset = point + offset
Format: yyyy-MM-dd, "o" for round-trip
Parse: TryParse, ParseExact + culture