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?
我有一个简单的控制台应用程序,该应用程序从SQL服务器获取数据。我必须使用SQL服务器中的日期和时间来搜索数据。如果我只输入年份,例如我输入2017年或2018年,则下面的代码有效,然后它获取当年所有数据,但如果我尝试在2017-07-22输入,那么它不会获得任何数据。我的SQL服务器的日期格式为年 - 月 - 日hh-mm-ss。我有点被困在这里。有什么建议么?
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}");
}
}
1 个解决方案
#1
3
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
#1
3
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