2011-09-07 154 views
0

我想計算我的SQL數據庫中字段'complaintdate'的天數。 在此字段中存儲用戶註冊投訴的日期。我希望從當前日期起,等待20天以上的投訴。計算天數

是否有其他函數或方法來計算天數? 我使用的代碼是

cmd = new SqlCommand("select complaintdate from complaintregister where compstatus='Attended & Open'", con); 
rd = cmd.ExecuteReader(); 
if (rd.Read()) 
{ 
    string s = rd["complaintdate"].ToString(); 
} 

我displayd 'S' 由

Response.Write(s); 

及其diplayed這種格式2011/4/5 12:00:00 AM

`

+0

complaintdate的數據類型是什麼?什麼是你的數據庫引擎? mysql? – confucius

回答

3

這將檢索totalDays作爲您的complaintDate到今天之間的天數。您檢索的手段替換GetDateFromDatabase()

DateTime complaintDate = GetDateFromDatabase(); 
int totalDays = (int)(DateTime.Now - complaintDate).TotalDays; 
if (totalDays >= 20) 
{ 
    // Perform your actions here. 20+ days have elapsed. 
} 

編輯:

我加入以下代碼使用您在編輯提供的代碼。我假設變量cmdconrd在您的代碼中的其他地方聲明。

cmd = new SqlCommand("select complaintdate from complaintregister where compstatus='Attended & Open' ", con);` 
rd = cmd.ExecuteReader(); 
if (rd.Read()) 
{ 
    string s = rd["complaintdate"].ToString(); 
} 

DateTime complaintDate; 
try 
{ 
    complaintDate = Convert.ToDateTime(s); 
} 
catch 
{ 
    Response.Write("An error occurred while trying to convert the date!"); 
    return; 
} 

int totalDays = (int)(DateTime.Now - complaintDate).TotalDays; 
if (totalDays >= 20) 
{ 
    // Perform your actions here. 20+ days have elapsed. 
} 
+0

其工作...但resul是155.450726453993 ...日期存儲在4/5/2011 12:00:00 AM格式 – Roshan

+0

我編輯它將'totalDays'轉換爲'int',所以它返回155沒有小數。爲了只顯示日期,請使用:'complaintDate.ToString(「m/d/yyyy」)' –

3

從你的問題,我不知道你是否想在數據庫或代碼中做這個比較。

如果要在SQL Server中執行檢查,可以使用DATEDIFF函數。

如果你想要做的代碼檢查,您可以使用DateTime.Subtract

var complaintDate = new DateTime(2011, 9, 1); 
var daysSinceComplaint = (int)DateTime.Now.Subtract(complaintDate).TotalDays; 
Console.WriteLine(daysSinceComplaint); 
0

在SQL Server另一種解決方案是把在計算字段中顯示多少天過去了表。如果CompliantDate爲空,將顯示爲空

ALTER TABLE ComplianceTable ADD 
DaysLapsed AS datediff(dd,CompliantDate,getdate()) 
GO 
+0

請注意我的解決方案會繞過日期格式等,因爲它會使用SQL Server日期時間幀,在C#中寫入if(dayslapsed> 20){DoSomething();} –