Limited Offer
60% OFF on all plans!

Date & Time in C#

Work with DateTime, DateOnly, TimeOnly (C# 10+), DateTimeOffset, TimeSpan, and format dates using ToString patterns and CultureInfo.

Introduction to Date & Time

What is Date & Time in C#?

Overview of C# date/time types and when to use each.

Creating Date Objects

Current Date & Time

Get the current local and UTC date/time.

Date from Specific Values

Construct a DateTime from year, month, day, hour, minute, second.

Date from Unix Timestamp

Convert a Unix timestamp (seconds since epoch) to DateTime.

Date from String

Parse a date string into a DateTime using Parse, TryParse, or ParseExact.

Timestamps

Getting Current Timestamp

Get the current Unix timestamp in seconds or milliseconds.

DateTime to Timestamp

Convert a DateTime value back to a Unix timestamp.

Getting Date Components

Date & Time Components

Extract year, month, day, hour, minute, second, and day-of-week.

UTC Components

Read components in UTC regardless of local timezone.

Formatting Dates

ToString & ISO Format

Convert DateTime to a string using built-in and ISO 8601 formats.

Locale & Custom Formatting

Format dates using CultureInfo for locale-aware output.

Comparing Dates

Comparing Two Dates

Use comparison operators and DateTime.Compare() to order dates.

Date Arithmetic

Adding & Subtracting

Add or subtract days, hours, months using Add* methods.

Difference Between Two Dates

Subtract two DateTimes to get a TimeSpan representing the duration.

Timezones & UTC

Local Time vs UTC

Convert between local time and UTC using TimeZoneInfo.

DateOnly & TimeOnly (C# 10+)

DateOnly

A date-only type with no time component — ideal for birthdays, deadlines.

TimeOnly

A time-only type with no date — ideal for opening hours, schedules.

Best Practices

Recommended Practices

Key rules for working safely with dates in C#.