I have created a function in C#, but it did not work as I expected. Today date is 06-10-2023 it should return FeesType 1 but it is returning 2. My code is here
using System.Globalization;
int value = GetFeesType();
Console.WriteLine("FeesType = {0}", value);
int GetFeesType()
{
int FeesType = 1;
DateTime TodayDate = DateTime.Now;
//TodayDate = Convert.ToDateTime("06-10-2023");
DateTime FeesType1 = DateTime.ParseExact("06-10-2023", "dd-MM-yyyy", null);
DateTime FeesType2 = DateTime.ParseExact("27-10-2023", "dd-MM-yyyy", null);
DateTime FeesType3 = DateTime.ParseExact("16-11-2023", "dd-MM-yyyy", null);
DateTime FeesType4 = DateTime.ParseExact("01-12-2023", "dd-MM-yyyy", null);
if (TodayDate <= FeesType1)
{
FeesType = 1;
}
else if (TodayDate <= FeesType2)
{
FeesType = 2;
}
else if (TodayDate <= FeesType3)
{
FeesType = 3;
}
else if (TodayDate <= FeesType4 || TodayDate > FeesType4)
{
FeesType = 4;
}
return FeesType;
}
How to fix it?
>Solution :
FeesType1
is 2023-10-06T00:00:00.000
TodayDate
was 2023-10-06T<something greater than 00:00:00>
hence TodayDate <= FeesType1
is in fact false
.
If you do not care for the exact time, switch to using DateOnly
or use DateTime.Date
and the behavior should be correct.