3

I want to compare two persian dates to find out which one is greater, I use this function :

public static List<MatchDrawHistory> GetAllMatchDrawHistory(string startDate, string endDate) 
{
    using (var db= new ReceiveSendEntitiesV5())
    {
        var matchDrawList = db.MatchDrawHistories.Where(x => String.CompareOrdinal(x.DrawStartDate,startDate)>=0 && String.CompareOrdinal(x.DrawEndDate , endDate) <=0).ToList();
        return matchDrawList;
    }
}

but it does not work, how can I do it?

EDIT: DrawStartDate and DrawStartDate are nvarchar(20) in DataBase, and these are persian date not gregorian date

majid zareei
  • 723
  • 6
  • 10
pmn
  • 2,176
  • 6
  • 29
  • 56

4 Answers4

2

First you need to convert your string date to DateTime. Assuming your string date is as yyyy/MM/dd, the conversion function can be as follow:

private static DateTime ParseDate(string date)
{
    var pc = new PersianCalendar();
    string[] arrDate = date.Split("/");

     return pc.ToDateTime(Int32.Parse(arrDate[0]), Int32.Parse(arrDate[1]), 
        Int32.Parse(arrDate[2]), 0, 0, 0, 0);
}

Now you can use the following method to compare two dates:

private static bool Compare(DateTime firstDate, DateTime secondDate)
{
    return firstDate >= secondDate;
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
majid zareei
  • 723
  • 6
  • 10
1

Your problem is that you're trying to store the dates as strings. I presume the dates in your class are strings, so I would pass in a DateTime, and use something like the following:

var matchDrawList = db.MatchDrawHistories.Where(x => DateTime.Parse(x.DrawStartDate) >= startDate && DateTime.Parse(x.DrawEndDate) <= endDate).ToList();

If you're not sure that the string will resolve to a date correctly, you could create a function to wrap a TryParse, depending on your business logic this may be preferable, as presumably you still want other results if one has an invalid date.

static bool CheckDateGreater(string date1, string date2)
{
    DateTime dt1;
    if (!DateTime.TryParse(date1, out dt) return false;

    DateTime dt2;
    if (!DateTime.TryParse(date2, out dt) return false;

    return (dt1 >= dt2);
}

Then call:

var matchDrawList = db.MatchDrawHistories.Where(x => CheckDateGreater(x.DrawStartDate, startDate) && CheckDateGreater(endDate, x.DrawEndDate).ToList();

EDIT:

Just seen your comment about Persian date. You need to use the PersianCalendar class. That should return you a DateTime object.

Paul Michaels
  • 16,185
  • 43
  • 146
  • 269
0

Use DateTime for the comparison rather than string

var start = DateTime.Parse(startDate);
var end = DateTime.Parse(endDate);
...
db.MatchDrawHistories.Where(x => x.DrawStartDate >= start && x.DrawEndDate <= end)
James
  • 80,725
  • 18
  • 167
  • 237
0

Use CompareTo method like below code: if(endDate.CompareTo(startDate) < 0) //startDate is greater