comparing months in words with date in digitd to get data

Viewed 33
    [HttpGet]
    public HttpResponseMessage Date(String date)
    {
        try
        {
            var users = db.Complains.Where(u => u.Date ==date ).ToList();
            return Request.CreateResponse(HttpStatusCode.OK, users);
        }
        catch (Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
        }
    }

In the above code, I am getting the data on entering date in yyy-mm-dd format but my requirement is getting month from user in (January, February) format and showing data of only that month. database picture is attached.

1 Answers

Algorithm :-

  1. First Change name of your parameter 'month'.

  2. Then put validation that if value of parameter is not in list of month in string. for that, you can create enum.

  3. Set 1, 2...12 values or enum and compare that value in linq to get desire output

    enum MonthsEnum { Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12 }
    
    [HttpGet]
    public HttpResponseMessage Date(String month)
    {
        try
        {
            //Convert month in enum;
             Enum.TryParse(month, out MonthsEnum givenMonth);
    
            if (givenMonth == 0)
              throw new Exception("Invalid Month");
    
            // if u.Date is date
            var users = db.Complains.Where(u => DateTime.Parse(u.Date) == (int)givenMonth).ToList();
    
           return Request.CreateResponse(HttpStatusCode.OK, users);
        }
        catch (Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
        }
    }
    
    

Use date format or culture info in date parse if needed

Related