【问题标题】:Parse date into dd-MMM-yy将日期解析为 dd-MMM-yy
【发布时间】:2013-08-27 19:14:45
【问题描述】:

朋友...

在我的 ms 访问数据库中,我存储日期格式 dd-MMM-yy。 并在搜索查询中将日期作为参数传递。 但我的系统不能包含日期格式 mm/dd/yyyy 那么,在将此日期传递给查询之前,我如何将这种格式转换为 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);

【问题讨论】:

  • 和enddate 也是DateTimePicker?

标签: c# ms-access-2007


【解决方案1】:

使用参数,不需要转成字符串

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 属性

【讨论】:

  • 看起来OP 不知道如何从DateTimePicker 中提取DateTime 值,您应该包含一个通知(他使用DateTimePicker.ToString() 来获取它的DateTime 值。跨度>
  • 可能值得补充一点,startdate.ToString() 返回 DTP 控件的字符串表示,只是为了澄清,但也许没有必要。
【解决方案2】:

使用parameter queries 是更好的选择,然后会处理这些格式问题。

对于当前的方法,一种解决方案是使用标准 ISO 日期格式 YYYY-MM-DD,将日期作为字符串传递:

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

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

Custom Date and Time Formats:MSDN

【讨论】:

    猜你喜欢
    • 2019-11-28
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2011-09-28
    • 2013-06-28
    • 2022-11-10
    • 1970-01-01
    • 2014-10-30
    相关资源
    最近更新 更多