Curriculum
DateTime
is a built-in value type in C# that represents a date and time. It is used extensively in many different types of applications, from simple console programs to complex web applications.
Here is an example of how to create a DateTime
object in C#:
DateTime dt = new DateTime(2023, 02, 23);
This creates a new DateTime
object representing the date and time February 23, 2023 at 12:00:00 AM.
The DateTime
type provides a wide range of methods and properties for working with dates and times. Here are some of the most commonly used methods:
AddDays
: Adds a specified number of days to the current DateTime
object.
DateTime dt = new DateTime(2023, 02, 23); DateTime newDt = dt.AddDays(7); // newDt = March 2, 2023
AddHours
: Adds a specified number of hours to the current DateTime
object.
DateTime dt = new DateTime(2023, 02, 23, 10, 0, 0); DateTime newDt = dt.AddHours(3); // newDt = February 23, 2023 1:00:00 PM
AddMinutes
: Adds a specified number of minutes to the current DateTime
object.
DateTime dt = new DateTime(2023, 02, 23, 10, 0, 0); DateTime newDt = dt.AddMinutes(30); // newDt = February 23, 2023 10:30:00 AM
AddMonths
: Adds a specified number of months to the current DateTime
object.
DateTime dt = new DateTime(2023, 02, 23); DateTime newDt = dt.AddMonths(1); // newDt = March 23, 2023
AddYears
: Adds a specified number of years to the current DateTime
object.
DateTime dt = new DateTime(2023, 02, 23); DateTime newDt = dt.AddYears(1); // newDt = February 23, 2024
Compare
: Compares two DateTime
objects and returns an integer indicating their relative values.
DateTime dt1 = new DateTime(2023, 02, 23); DateTime dt2 = new DateTime(2024, 02, 23); int result = DateTime.Compare(dt1, dt2); // result = -1
Equals
: Determines whether two DateTime
objects are equal.
DateTime dt1 = new DateTime(2023, 02, 23); DateTime dt2 = new DateTime(2023, 02, 23); bool isEqual = dt1.Equals(dt2); // isEqual = true
Parse
: Converts a string representation of a date and time into a DateTime
object.
string str = "2023-02-23 10:00:00"; DateTime dt = DateTime.Parse(str); // dt = February 23, 2023 10:00:00 AM
TryParse
: Tries to convert a string representation of a date and time into a DateTime
object, and returns a Boolean value indicating whether the conversion succeeded or failed.
string str = "2023-02-23 10:00:00"; DateTime dt; bool success = DateTime.TryParse(str, out dt); // success = true, dt = February 23
Â