简体   繁体   English

从C#中的sql使用日期和时间获取数据

[英]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. 我有一个简单的控制台应用程序,该应用程序从SQL服务器获取数据。 I have to search data using date and time from the SQL server. 我必须使用SQL服务器中的日期和时间来搜索数据。 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. 如果我只输入年份,例如我输入20172018 ,则下面的代码有效,然后它获得当年所有数据,但如果我尝试在2017-07-22输入,那么它不会获得任何数据。 My SQL server has date format of year-month-day hh-mm-ss . 我的SQL服务器的日期格式为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: 要使用确切的格式进行解析,您可以使用DateTime.TryParseExact这样,基于您提供的格式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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