Ilorra
Ilorra

Reputation: 21

How to filter string date?

I'm working on a date, which i need to filter because the data was too big. This is the code i tried so far.

string value = Datetime.Now.tostring("yyyy-MM-dd");
DateTime fromdate;
fromdate = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd");
DateTime todate;
todate = DateTime.Now.ToString("yyyy-MM-dd");

 if((value >= fromdate) && (value <= todate))
{
//filtered items
}

The Error always say's

Operator >= cannot be applied to operand of type string and System datetime

In which part of my code is wrong ?

Upvotes: 1

Views: 2037

Answers (4)

Salah Akbari
Salah Akbari

Reputation: 39946

You need to convert to a date by using DateTime.Parse Method:

if ((DateTime.Parse(value) >= fromdate && ((DateTime.Parse(value) <= todate))

This code works fine:

string value = DateTime.Now.ToString("yyyy-MM-dd");
DateTime fromdate;
fromdate = DateTime.Now.AddDays(-2);
DateTime todate;
todate = DateTime.Now;

if ((DateTime.Parse(value) >= fromdate && ((DateTime.Parse(value) <= todate))))
{
    //filtered items
}

Upvotes: 2

Emond
Emond

Reputation: 50672

var now = Datetime.Now;
var value = now.Date;
var fromdate = now.AddDays(-2).Date;
var todate = now.Date;

if((value >= fromdate) && (value <= todate))
{
    //filtered items
}

This can be simpler because value and todate are always the same and value is always more than fromdate. So the if condition is always true.

Upvotes: 0

Saif
Saif

Reputation: 2679

It doesn't need to parse or convert date, you can deal with date directly

DateTime val = DateTime.Now.Date;

DateTime fromdate = DateTime.Now.AddDays(-2).Date;

DateTime todate = DateTime.Now;

if((val >= fromdate) && (val <= todate))
{
//filtered items
  Console.WriteLine("do something");
}

Upvotes: 3

Supun De Silva
Supun De Silva

Reputation: 1487

Does this line compile ?

fromdate = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd");

You are defining fromdate as DateTime and trying to assign a string to it

DateTime fromdate;
fromdate = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd");

Same applies to toDate

Upvotes: 1

Related Questions