Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a DataTable using DateTime value

Tags:

c#

Updated:

I am trying to filter a DataTable based on a particular date. My datatable has a column "whn" which contains dates. A Sample date from the DataTable:

{21/02/2012 10:03:53}   object {System.DateTime}

Here is the code I am using to try and filter the DataTable:

 String datevalue= "21/02/2012 10:03:53";

  DataRow[] foundRows;
  foundRows = dttemp.Select(String.Format("whn = '{0}'", datevalue));

However this does not work and returns 0 rows. Even though I know that a row containing the date in "datevalue" exists.

Unsure why this is not working, any help is appreciated.

Thanks.

like image 688
Jonathon Fry Avatar asked Mar 07 '26 17:03

Jonathon Fry


2 Answers

If you want to exactly match the supplied DateTime, including fractions of a second, you should use a DateTime format that has enough precision. Probably the round-trip format ("o") is a good bet:

foundRows = dttemp.Select(String.Format(dttemp.Locale, "whn = '{0:o}'", datevalue));

However, it's more likely you want to match values that fall into a range. For example, if you want all values that have the same date, but any time of day, you could use:

foundRows = dttemp.Select(String.Format(dttemp.Locale, "whn >='{0:o}' AND whn < '{1:o}'",
      datevalue.Date, datevalue.AddDays(1).Date));

Similarly if you want all values that are in the same second (but may have fractions of a second), you can use:

DateTime from = dttemp.AddTicks( - (dttemp.Ticks % TimeSpan.TicksPerSecond));
foundRows = dttemp.Select(String.Format(dttemp.Locale, "whn >='{0:o}' AND whn < '{1:o}'",
      from, from.AddSeconds(1)));

The call to AddTicks truncates the supplied DateTime to a whole number of seconds, as described in the accepted answer to this StackOverflow question.

Note I used dttemp.Locale to use the correct locale (CultureInfo) in case your DataTable has a locale other than your current culture.

like image 103
Joe Avatar answered Mar 09 '26 06:03

Joe


foundRows = dttemp.Select("whn LIKE '{0}'",datevalue);

should probably be

foundRows = dttemp.Select(String.Format("whn LIKE '{0}'",datevalue));

more info here http://www.csharp-examples.net/dataview-rowfilter/

like image 29
enz0 Avatar answered Mar 09 '26 07:03

enz0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!