user96564
user96564

Reputation: 1607

Get data using Date and Time from sql in C#

I have a simple console application and this application gets data from the SQL server. I have to search data using date and time from the SQL server. This below code works if I enter only the year for example if I enter 2017 or 2018, then it gets data of all that year but if I try to enter in 2017-07-22, then it doesn't get any data. My SQL server has date format of year-month-day hh-mm-ss. I am kind of stuck here. Any suggestions?

using (var context = new Model1())
{
    Console.WriteLine("Enter Date");
    DateTime dateTime;
    var s = dateTime.ToShortDateString();
    s = Console.ReadLine();

    var result = context.Databases.
        Where(x => x.RecordedTime.Value.ToString().
        Contains(s)).ToList(); ;

    foreach (var item in result)
    {
        Console.WriteLine($"{item.RecordedTime.Value.ToShortDateString()}, {item.Temperature}");
    }

}

Upvotes: 1

Views: 1110

Answers (1)

Guilherme Holtz
Guilherme Holtz

Reputation: 485

You don't need to convert to string, you need to only parse it. To parse with an exact format you can use DateTime.TryParseExact like this, based in the format you provided:

s = Console.ReadLine();

DateTime dt;
DateTime.TryParseExact(s, 
    "yyyy-MM-dd HH-mm-ss", 
    CultureInfo.InvariantCulture, 
    DateTimeStyles.None, 
    out dt);

//... do linq stuff with variable dt

Upvotes: 3

Related Questions