WouldBeNerd
WouldBeNerd

Reputation: 687

How to do Linq to SQL dateTime Filter

I I'm new to C# coming from VB and im trying to get this sql-linq query to work. It works without the IEnumerable date filter. But I'm not getting any error messages or syntax errors either. Can anyone tell me what I'm missing? I could do it by pulling the whole table and then applying the filter, but i don't want to do that because there are too many records. I've mostly been following this tutorial to get me on the right path.

[http://www.codeproject.com/Articles/43025/A-LINQ-Tutorial-Mapping-Tables-to-Objects][1]

This is the code I'm currently using

public void getdata() 
{
    Console.WriteLine("starting");

    var STL = new STDB.reportDB(Properties.Settings.Default.dataConnString);

    DateTime startDate = new DateTime(01 / 02 / 2015);
    DateTime endDate = new DateTime(01 / 03 / 2015);

    IEnumerable<STDB.salesInvLine> lastMonthInvoiced = 
          from salesinv in STL.Sales_Inv_Lines
          where (salesinv.Shipment_Date.Year == startDate.Year
                 && salesinv.Shipment_Date.Month == startDate.Month)
          select salesinv;

    foreach (STDB.salesInvLine salesinv in lastMonthInvoiced) 
    {
        string code = salesinv.Document_No_;
        DateTime ddate = salesinv.Shipment_Date;
        Console.WriteLine(code);
    }
}

I think that in the where line all go wrong, but I really not sure.I've made sure that the field is a DateTime field in the database.

Other examples I found had DateTime defined with quotes but my Visual Studio wouldn't accept a string as a datetime like this DateTime("01/03/2015").

Any help would be much appreciated.

Upvotes: 1

Views: 1749

Answers (2)

Juan
Juan

Reputation: 3705

Try creating the dates this way:

DateTime startDate = new DateTime(2015, 2, 1);
DateTime endDate = new DateTime(2015, 3, 1);

Without the quotes you are using actually the constructor that takes an int (you are dividing) and that int means ticks!

EDITED: There is no constructor for DateTime taking string as parameter

You can try:

var myDate = Datetime.Parse("31/01/2015")

But bear in mind your current locale as that datetime format could means different things based on that.

Upvotes: 1

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98868

First thing I see

DateTime startDate = new DateTime(01 / 02 / 2015);
DateTime endDate = new DateTime(01 / 03 / 2015);

lines should be

DateTime startDate = new DateTime(2015, 2, 1);
DateTime endDate = new DateTime.Parse(2015, 3, 1);

Because, you know, 01 / 02 / 2015 and 01 / 03 / 2015 generates 0 because they are integer divisions. We know them from elementary school. Both calls DateTime(Int64) constructor as DateTime(0) which is equal to DateTime.MinValue.

Or if this is a string date and time format of your CurrentCulture, you can use;

DateTime startDate = DateTime.Parse("01/02/2015");
DateTime endDate = DateTime.Parse("01/03/2015");

Upvotes: 0

Related Questions