Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Date comparison function not work as expected ASP.NET

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading