开发者

C# comparing Date & Time in Linq

开发者 https://www.devze.com 2023-03-31 23:50 出处:网络
Using linq, i want to return only those records whose date & time is greater than the provided date. The record has date and time in different columns in string formats.

Using linq, i want to return only those records whose date & time is greater than the provided date. The record has date and time in different columns in string formats. For e.g., "290811" for (29/Aug/2011) and "1400" for (2 PM or 14 hours depending on the context it's being used).

What i have done:

var result = from s in source
             where GetDateTime(s.date, s.time) >= myDateTime
             select s;

GetDateTime is a function i've created to return the date and time in DateTime format. myDatetime is the date i'm passing.

Edit: Functions Used:

public static DateTime GetDateTime(string strDate, string strTime) {
    DateTime dt;
    int dd = Convert.ToInt32(strDate.Substring(0, 2));
    int mm = Convert.ToInt32(strDate.Substring(2, 2));
    int yy = Convert.ToInt32("20" + strDate.Substring(4, 2));

    TimeSpan ts = GetTimeFromString(strTime);

    dt = new DateTime(yy, mm, dd, ts.Hours, ts.Minutes, 0);            

    return dt;
}

public static TimeSpan GetTimeFromString(string strTime) {
    int hh = Convert.ToInt32(strTime.Substring(0, 2));
    int mins = Convert.ToInt32(strTime.Substring(2, 2));        
    return new TimeSpan(hh, mins, 0);
}

Sample Data:

Adt_avlStatus   7
Adt_BaseFare    100
Adt_breakPoint  Y
Adt_cabin       M
Adt_Discount    0
Adt_Farebasis   EAP14DN
Adt_fareType    RP
Adt_Markup      0
Adt_rbd     E
date        290811
time        1520
Origin      IXC
Destination     GOI

myDateTime sample: 20/08/2011 17:35:00 (20/Aug/2011 5:35 PM)

The problem is that the above linq is not filtering the results as it should. Please tell m开发者_JS百科e what i'm doing wrong. Thanks.


I assume, myDateTime also contains a time part. If I understood you correctly, you want myDateTime to only contain a date part. You can verify this: myDateTime contains a time part, if myDateTime != myDateTime.Date.


Judging by what is visible in your question, the bug is GetDateTime, s.date or s.time. Are you sure GetDateTime is working correctly?


If it does not filter the results as it should, your GetDateTime() method must be flawed.


Without the data we can still only speculate.

The problem is either:

  • an incorrect value coming back from GetDateTime because the input data from source was not in the format you expect
  • the value of myDateTime is either not set or set too low, which means all dates in your incoming data are greater than it


try

var result = from s in source let dt = GetDateTime(s.date, s.time)
             where dt >= myDateTime
             select s;
0

精彩评论

暂无评论...
验证码 换一张
取 消