DateTime
object CS-W1080The DateTime
constructor allows you to specify the year, month, day, and time to construct a DateTime
object. However, this constructor throws an ArgumentOutOfRangeException
exception if the specified date is invalid.
The use of addition and subtraction operations can lead to the creation of invalid dates. Instead, it is recommended that you use APIs such as AddDays()
, AddMonths()
, and AddYears()
to construct a DateTime
object since these methods handle invalid dates more appropriately.
var now = DateTime.Now;
// Throws `ArgumentOutOfRangeException` exception if `now` points to Jan 29.
new DateTime(now.Year, now.Month + 1, now.Day + 1, 0, 0, 0, DateTimeKind.Utc);
var now = DateTime.Now;
// Rolls over appropriately without throwing an `Exception`.
var next = now.AddDays(1).AddMonths(1);