DateTime.Now / DateTime.Today
DateTime.Now retrieves the current date and time, and DateTime.Today retrieves today's date with the time set to 00:00:00.
Syntax
// Gets the current date and time (local time). DateTime variable = DateTime.Now; // Gets today's date (time is 00:00:00). DateTime variable = DateTime.Today; // Gets the current UTC date and time. DateTime variable = DateTime.UtcNow;
Member List
| Member | Description |
|---|---|
| DateTime.Now | Returns the current local date and time (year, month, day, hour, minute, second). |
| DateTime.Today | Returns today's date. The time portion is set to 00:00:00. |
| DateTime.UtcNow | Returns the current UTC date and time. Recommended for server-side processing and logging. |
| .Year / .Month / .Day | Gets the year, month, or day as an integer. |
| .Hour / .Minute / .Second | Gets the hour, minute, or second as an integer. |
| .DayOfWeek | Returns the day of the week as a DayOfWeek enum value (e.g., DayOfWeek.Monday). |
Sample Code
using System;
// Gets the current date and time.
DateTime now = DateTime.Now;
Console.WriteLine(now); // e.g., 2024/01/15 14:30:45
// Gets today's date (no time component).
DateTime today = DateTime.Today;
Console.WriteLine(today); // e.g., 2024/01/15 0:00:00
// Gets each component individually.
Console.WriteLine($"Year: {now.Year}");
Console.WriteLine($"Month: {now.Month}");
Console.WriteLine($"Day: {now.Day}");
Console.WriteLine($"Hour: {now.Hour}");
Console.WriteLine($"Minute: {now.Minute}");
Console.WriteLine($"Second: {now.Second}");
// Gets the day of the week.
Console.WriteLine($"Day of week: {now.DayOfWeek}");
// Displays the day of the week as a short name.
string[] dayNames = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
Console.WriteLine($"Day of week (short): {dayNames[(int)now.DayOfWeek]}");
// Gets the current UTC time.
DateTime utc = DateTime.UtcNow;
Console.WriteLine($"UTC: {utc}");
Overview
Both DateTime.Now and DateTime.Today are static properties. Since they retrieve the current time each time they are called, store the value in a variable if you need to use it multiple times within the same operation.
For logging and database storage, use DateTime.UtcNow, which is not affected by time zone differences. To format a date and time as a string, see DateTime.ToString() / DateTime.AddDays().
If you find any errors or copyright issues, please contact us.