There is an error in the second part of Grant Winnie's code. The assignment after the IsLeapYear check is reversed. The correct code is:
public static bool IsValidYearMonthDay(int year, int month, int day) { if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) { int[] days = DateTime.IsLeapYear(year) ? new[] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 } : new[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; if (day >= 1 && day <= days[month] - days[month - 1]) { return true; } } return false; }
And the test:
[TestCase(2019, 10,21,true)] [TestCase(2019, 11, 31, false)] //november doesnt have 31, only 30 [TestCase(2016, 2, 29, true)] // is leap [TestCase(2014, 2, 29, false)] // is nop leap public static void ValidateYearMonthDay(int year, int month, int day, bool expectedresult) { var result = Date.IsValidYearMonthDay(year, month, day); Assert.AreEqual(expectedresult, result); }