C# 将日期解析为dd-MMM-yy
朋友们 在我的ms access数据库中,我存储日期格式dd MMM yy。 并在搜索查询中将传递日期作为参数。 但我的系统的日期格式是mm/dd/yyyy 那么,在传递此日期到查询之前,如何将此格式转换为dd-MMM-yy 现在,我正在使用错误代码..但给出错误..字符串未被识别为有效的日期时间C# 将日期解析为dd-MMM-yy,c#,ms-access-2007,C#,Ms Access 2007,朋友们 在我的ms access数据库中,我存储日期格式dd MMM yy。 并在搜索查询中将传递日期作为参数。 但我的系统的日期格式是mm/dd/yyyy 那么,在传递此日期到查询之前,如何将此格式转换为dd-MMM-yy 现在,我正在使用错误代码..但给出错误..字符串未被识别为有效的日期时间 DateTime dt = DateTime.ParseExact(startdate.ToString(), "dd-MMM-yy",
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);
使用参数,不需要转换为字符串
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
}
}
请注意,您可以直接从日期时间选择器控件获取选定的日期时间值。使用DateTimePicker.Value属性使用是更好的选择,这样就可以解决这些格式问题
对于当前方法,解决方案是使用标准ISO日期格式YYYY-MM-DD,将日期作为字符串传递:
string sStartDate = startdate.Value.ToString("yyyy-MM-dd");
".. and odate >= #" + sStartDate + "#..
:MSDN并且enddate也是一个DateTimePicker?看起来OP不知道如何从DateTimePicker中提取DateTime值,您应该包括一个通知,说明他使用DateTimePicker.ToString获取其DateTime值。可能值得添加startdate.ToString返回DTP控件的字符串表示形式,我只是想澄清一下,但也许没有必要。