簡體   English   中英

如何使用C#從今天的日期和當前時間獲得3個月前的日期和時間

[英]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)

AddMonths方法中使用-3作為參數

DateTime dtPreviousDate = DateTime.Now.AddMonths(-3);

DateTime.AddMonths方法

好幾個月了。 月份參數可以是負數或正數。

你可以嘗試這個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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM