2013-08-27 29 views
0

朋友...解析日期到dd-MMM-yy

在我的MS訪問數據庫我存儲日期格式dd-MMM-yy。 並在搜索查詢中傳遞日期作爲參數。 但我的系統cantain日期格式mm/dd/yyyy 因此,如何在dd-MMM-yy中將此格式轉換爲現在查詢 之前,我使用folling代碼..但給錯誤....字符串未被視爲有效的日期時間。

DateTime dt = DateTime.ParseExact(startdate.ToString(), "dd-MMM-yy", 
            CultureInfo.InvariantCulture);//startdate is datepicker 

查詢...

s = new OleDbDataAdapter(" 
     SELECT opd_patient_master.*, patient_operation.* 
     FROM opd_patient_master, patient_operation 
     WHERE opd_patient_master.pid= patient_operation.pid 
     and opd_patient_master.rdid= patient_operation.rdid 
     and odate >= #" + startdate + "# and odate<=# " + enddate + "# 
     and operation= '" + oprtype + "'", mycon); 
+0

和'enddate'也是一個'DateTimePicker'? –

回答

2

使用參數,你不需要轉換爲字符串

using (var cmd = new OleDbCommand("SELECT opd_patient_master.*, patient_operation.* FROM opd_patient_master, patient_operation where opd_patient_master.pid= patient_operation.pid and opd_patient_master.rdid= patient_operation.rdid and odate >= ? and odate<= ? and operation= ?", mycon)) 
{ 
    cmd.Parameters.AddWithValue("@startdate", startDateTimePicker.Value); // use DateTime input here as startdate 
    cmd.Parameters.AddWithValue("@enddate", endDateTimePicker.Value); // use DateTime input here as enddate 
    cmd.Parameters.AddWithValue("@oprtype", oprtype); 
    using (OleDbDataAdapter s = new OleDbDataAdapter(cmd)) 
    { 
     // do something with adapter 
    } 

} 

請注意,您可以從日期時間選擇器選擇DateTime值直接控制。使用DateTimePicker.Value屬性

+1

看起來'OP'不知道如何從DateTimePicker中提取DateTime值,你應該包含一個關於它的通知(他使用'DateTimePicker.ToString()'來獲得它的DateTime值。 –

+0

@KingKing好點,回答更新 – Damith

+0

可能值得補充的是,'startdate.ToString()'返回DTP控件的字符串表示形式,只是爲了說明,但可能不是必需的。 –

0

使用parameter queries是更好的選擇,那麼這些格式問題將被照顧。

對於當前的方法中,解決方案是使用標準ISO日期格式YYYY-MM-DD,傳遞日期的字符串:

string sStartDate = startdate.Value.ToString("yyyy-MM-dd"); 

".. and odate >= #" + sStartDate + "#.. 

Custom Date and Time Formats:MSDN