Sang Suantak
Sang Suantak

Reputation: 5265

C# comparing Date & Time in Linq

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 me what i'm doing wrong. Thanks.

Upvotes: 1

Views: 1684

Answers (5)

Yahia
Yahia

Reputation: 70379

try

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

Upvotes: 0

slugster
slugster

Reputation: 49985

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

Upvotes: 0

Jacek Gorgoń
Jacek Gorgoń

Reputation: 3214

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

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

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.

Upvotes: 1

Bas
Bas

Reputation: 27115

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

Upvotes: 0

Related Questions