C# DateTime is a value type (struct) that represents a specific date and time. It's found in System namespace. This feature comes in handy whenever we need to work with date and time.
We can create or instantiate a DateTime object as follows:
DateTime date = new DateTime(2019, 03, 29, 15, 0, 0);
In the above example year, month, day, hour, minutes and seconds have been provided as an argument. If we print date using Console.WriteLine() then it will show following output.
Console.WriteLine(date) //-->/29/2019 3:00:00 PM
We can also use the same principle to create a DateTime object representing the current date and time
DateTime now = DateTime.Now;
We can compare the two dates
if (date > now)
{
Console.WriteLine(true);
}
else Console.WriteLine(false);
Above example prints false as the date is smaller than the now.
We can also format DateTime object as per our requirements. An example static method is shown below
public static string Description(DateTime appointmentDate)
{
return $"You have an appointment on {appointmentDate.ToString("M/d/yyyy h:mm:ss tt")}."; //formatted in month/day/year hour:minutes:seconds AM/PM
//-->You have an appointment on month/day/year hour:minutes:seconds AM/PM
}
In the above static method argument appointmentDate must be a DateTime object. ToString method is used to convert the DateTime object to string.
We can also convert string to date using a .Parse()
method. An example is shown below.
public static DateTime Schedule(string appointmentDateDescription)
{
return DateTime.Parse(appointmentDateDescription);
}
var date = Appointment.Schedule("20 January 2023");
Console.WriteLine(date); //--> 20/01/2023 00:00:00
In the above example var is assigned to date and compiler assigns the appropriate data type based on the value i.e. in this case DateTime data type. We can also directly use DateTime data type. There are numerous DateTime pre-built methods. Please refer to Microsoft documentation.