简体   繁体   中英

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}");
    }

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM