How to compare two persian date to find out which one is greater?

北城余情 提交于 2019-12-24 00:38:15

问题


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


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




回答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;
}



回答3:


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)


来源:https://stackoverflow.com/questions/25947010/how-to-compare-two-persian-date-to-find-out-which-one-is-greater

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!