العمل مع
What is it and why? (a real-life analogy)
Imagine you are the captain of a spaceship cruising through the universe. You have two main instruments on board: a chronometer (which shows the current moment in time) and a logbook (where you record events). Without them, you would be lost in time and space: you wouldn't know when you took off, when you need to land, or how much fuel you've spent in the last hour.
In programming, it's exactly the same. Any program that interacts with the real world deals with dates and times. This could be:
- A task calendar — to remind you of a friend's birthday in 3 days.
- A banking app — to show the transaction history for the last month.
- A game — to calculate how much time a player spent online.
- A server — to log the exact time of an error.
Without the ability to work with dates and times, any program would be blind and deaf to the real world. In C# (.NET), there is a powerful tool for this — the DateTime structure and its friends. Let's figure out how they work.
Important: In C#, a date and time is not just a string like "05/12/2024". It is a special data type that stores time as a number (a count of ticks) and can perform mathematical operations on it.
Theory: how it works internally
The foundation of working with dates and times in .NET is the DateTime structure. It stores a moment in time with an accuracy of 100 nanoseconds (this is called a "tick"). One tick = 100 nanoseconds = 0.0001 milliseconds.
How is it structured internally?
Imagine we have a huge number line. The starting point (point 0) is January 1, 0001 at 00:00:00 (midnight). Each subsequent moment in time is simply the number of ticks that have passed from this point. For example:
- January 1, 2024 — this is approximately 638,000,000,000,000 ticks from the starting point.
- This evening — that's a few more million ticks added.
This approach allows you to:
- Compare dates (earlier/later) — simply compare two numbers.
- Subtract dates — get the difference as a time interval.
- Add days, hours, minutes — simply add the required number of ticks.
Important structures and classes:
| Type | Description | Example |
|---|---|---|
DateTime |
A moment in time (date + time) | 05/12/2024 15:30:00 |
TimeSpan |
A period of time (interval) | 3 days 5 hours 10 minutes |
DateOnly |
Date only (without time) — introduced in .NET 6 | 05/12/2024 |
TimeOnly |
Time only (without date) — introduced in .NET 6 | 15:30:00 |
DateTimeOffset |
Date and time with an offset relative to UTC | 05/12/2024 15:30:00 +03:00 |
Tip: Always use DateTimeOffset for storing dates in databases or when transferring between systems. This will save you from confusion with time zones.
Syntax in C# (.NET): all forms and options
Creating DateTime objects
There are several ways to create a date and time:
// Method 1: Current time
DateTime now = DateTime.Now; // Local time (considering time zone)
DateTime utcNow = DateTime.UtcNow; // Coordinated Universal Time (UTC)
// Method 2: Specific date
DateTime birthday = new DateTime(2005, 5, 15); // May 15, 2005, 00:00:00
DateTime meeting = new DateTime(2024, 12, 25, 14, 30, 0); // December 25, 2024, 14:30:00
// Method 3: From a string (parsing)
string dateString = "2024-05-12";
DateTime parsedDate = DateTime.Parse(dateString); // Can throw an exception if the string is invalid
// Method 4: Safe parsing
if (DateTime.TryParse("2024-05-12", out DateTime safeDate))
{
Console.WriteLine($"Successfully parsed: {safeDate}");
}
else
{
Console.WriteLine("Failed to parse the date");
}
// Method 5: From ticks
long ticks = 638000000000000000;
DateTime fromTicks = new DateTime(ticks);
Basic properties and methods
| Property/Method | Description | Example |
|---|---|---|
.Year |
Year (int) | 2024 |
.Month |
Month (1-12) | 5 |
.Day |
Day of the month (1-31) | 12 |
.Hour |
Hours (0-23) | 15 |
.Minute |
Minutes (0-59) | 30 |
.Second |
Seconds (0-59) | 45 |
.DayOfWeek |
Day of the week (enum) | DayOfWeek.Sunday |
.DayOfYear |
Day of the year (1-366) | 133 |
.AddDays(n) |
Add n days | date.AddDays(5) |
.AddMonths(n) |
Add n months | date.AddMonths(-2) |