Current Date and Time:
Now: Gets the current date and time.
DateTime now = DateTime.Now;
UtcNow: Gets the current date and time in Coordinated Universal Time (UTC).
DateTime utcNow = DateTime.UtcNow;
Specific Date and Time:
Constructor: Creates a specific date and time.
DateTime specificDate = new DateTime(2024, 7, 31, 14, 30, 0);
Today: Gets the current date with the time component set to 00:00:00.
DateTime today = DateTime.Today;
Parsing:
Parse: Converts the string representation of a date and time to its 'DateTime' equivalent.
DateTime parsedDate = DateTime.Parse("2024-07-31");
TryParse: Tries to convert the string representation of a date and time to its 'DateTime' equivalent and returns a boolean indicating success or failure.
DateTime result;
bool success = DateTime.TryParse("2024-07-31", out result);
DateTime Properties:
Year, Month, Day: Gets the year, month, and day components of the date.
int year = now.Year;
int month = now.Month;
int day = now.Day;
Hour, Minute, Second: Gets the hour, minute, and second components of the time.
int hour = now.Hour;
int minute = now.Minute;
int second = now.Second;
DayOfWeek: Gets the day of the week.
DayOfWeek dayOfWeek = now.DayOfWeek;
DayOfYear: Gets the day of the year.
int dayOfYear = now.DayOfYear;
DateTime Methods:
Adding and Subtracting:
AddDays, AddMonths, AddYears: Adds the specified number of days, months, or years to the date.
DateTime nextWeek = now.AddDays(7);
DateTime nextMonth = now.AddMonths(1);
DateTime nextYear = now.AddYears(1);
AddHours, AddMinutes, AddSeconds: Adds the specified number of hours, minutes, or seconds to the time.
DateTime inTwoHours = now.AddHours(2);
DateTime inThirtyMinutes = now.AddMinutes(30);
DateTime inTenSeconds = now.AddSeconds(10);
Subtract:
Subtract: Subtracts a specified time interval from the date.
TimeSpan duration = new TimeSpan(1, 0, 0, 0); // 1 day
DateTime yesterday = now.Subtract(duration);
Comparison:
CompareTo: Compares two DateTime instances.
int comparison = now.CompareTo(specificDate);
Equals: Checks if two DateTime instances are equal.
bool isEqual = now.Equals(specificDate);
Before, After: Checks if one date is before or after another date.
bool isBefore = specificDate < now;
bool isAfter = specificDate > now;
Formatting DateTime:
ToString: Converts the DateTime to its string representation.
string dateString = now.ToString();
ToString with format: Converts the DateTime to its string representation with a specified format.
string formattedDate = now.ToString("yyyy-MM-dd HH:mm:ss");
Top comments (0)