![](/img/trans.png)
[英]how to get exact 3 months ago date and time from today's date and current time using C#
[英]Get data using Date and Time from sql in C#
我有一個簡單的控制台應用程序,該應用程序從SQL服務器獲取數據。 我必須使用SQL服務器中的日期和時間來搜索數據。 如果我只輸入年份,例如我輸入2017
或2018
,則下面的代碼有效,然后它獲得當年所有數據,但如果我嘗試在2017-07-22
輸入,那么它不會獲得任何數據。 我的SQL服務器的日期格式為year-month-day 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}");
}
}
您不需要轉換為字符串,只需要解析它。 要使用確切的格式進行解析,您可以使用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.