In C#, the DateTime struct is a fundamental data type used for working with dates and times. It is part of the System namespace and provides a wide range of methods and properties for handling date and time information
You can create a DateTime object to represent a specific date and time. There are several constructors available, but the most common one takes year, month, day, hour, minute, and second as parameters:
To get the current date and time, you can use the DateTime.Now property:
You can format a DateTime object into a string using the ToString method or specifying a format string:
DateTime provides various properties to access different components of the date and time:
You can perform arithmetic operations with DateTime objects, such as adding or subtracting time intervals:
You can compare DateTime objects using comparison operators (<, <=, >, >=) or the Equals method.
To handle time zones, you can use the DateTimeOffset struct. It includes offset information, making it suitable for working with date and time in a specific time zone.
The DateTime represents the date and time.
The offset represents the difference between the local time and UTC.
You can parse date and time strings using the DateTime.Parse or DateTime.TryParse method.
In C#, the DateTime.ParseExact method is used to parse a string that represents a date and time into a DateTime object, based on a specified format. This method is particularly useful when you have a date and time string in a specific format and you want to ensure that it is correctly parsed according to that format.
// Date and time string in a specific format
// Date format string corresponding to the input format
// Parse the date string using the specified format
// Display the parsed date and time
// Date and time string in a specific format
// Date format string corresponding to the input format
// Parse the date string using the specified format
// Display the parsed date and time
The DateTime struct allows you to perform various calculations and manipulations of date and time, such as calculating differences between two dates, finding the day of the week, or determining leap years.
The DateTime struct is a fundamental and powerful component of C# for handling date and time information, and it is essential for various applications, including scheduling, logging, and working with historical data.