[英]how to get exact 3 months ago date and time from today's date and current time using C#
我想從過去3個月保存的數據庫獲取數據,因為我有當前的日期和時間,但是如何計算3個月的自我日期和時間,這樣我可以在查詢中傳遞這2個日期並獲取數據在這些日期之間保存
使用AddMonths
方法 :
DateTime ago = DateTime.Now.AddMonths(-3);
嘗試這個:
DateTime.Now.AddMonths(-3)
你可以嘗試這個DateTime.Now.AddMonths(-3)
AddMonths
可能是負面的。
DataTable tblResult = new DataTable();
string sql = "SELECT * FROM dbo.TableName WHERE Date BETWEEN @startDate AND @endData";
using (var con = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, con))
using (var da = new SqlDataAdapter(cmd))
{
// asuming that your startdate is three months ago and your enddate is now
cmd.Parameters.AddWithValue("@startDate", DateTime.Now.AddMonths(-3));
cmd.Parameters.AddWithValue("@endDate", DateTime.Now);
da.Fill(tblResult);
}
DateTime now = DateTime.Now;
DateTime olddate = new DateTime(now.Year,now.Month - 3,now.Day);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.