c#两个日期之间的差异

本文关键字:之间 日期 两个 | 更新日期: 2023-09-27 18:19:56

在我的GridView中,我有一个方法调用DisplayWarning()

我想计算日期列(在我的SQL server中)和DateTime之间的时差。现在,在GridView中显示我的一个StatusIMG,这是GridView的代码:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="InvoiceID" DataSourceID="SqlDataSource1" CssClass="table table-striped table-bordered" AllowPaging="True" AllowSorting="True">
<Columns>
    <asp:BoundField DataField="InvoiceID" HeaderText="Rechnung Identifikation" InsertVisible="False" ReadOnly="True" SortExpression="InvoiceID" />
    <asp:BoundField DataField="CustomerID" HeaderText="Kunde Identifikation" SortExpression="CustomerID" />
    <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
    <asp:BoundField DataField="Amount" HeaderText="Betrag" SortExpression="Amount" />
    <asp:BoundField DataField="Paid" HeaderText="Bezahlter Betrag" SortExpression="Paid" />
    <asp:BoundField DataField="Rest" HeaderText="Rest" SortExpression="Rest" />
    <asp:BoundField DataField="PaymentType" HeaderText="Zahlungsart" SortExpression="PaymentType" />
    <asp:CheckBoxField DataField="Shipped" HeaderText="erledigt" SortExpression="Shipped" />
    <asp:TemplateField>
    <ItemTemplate>
    <asp:Image runat="server" ImageUrl='<%# DisplayWarning() %>' Width="16" />     
    </ItemTemplate>
    </asp:TemplateField>
</Columns>

这就是DisplayWarning()方法:

public string DisplayWarning()
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RechnungConnectionString"].ConnectionString);
    conn.Open();
    SqlCommand datecmd = new SqlCommand("Select DATEDIFF(day,Date,Getdate()) as DiffDate From Invoice", conn);
    SqlDataReader Reader = datecmd.ExecuteReader();
    int RegTime;
    Reader.Read();
    RegTime = Convert.ToInt32(Reader["DiffDate"]); 
    string StatusColor;
    if (RegTime < 7)
    {
        StatusColor = "Image/green-4040.jpg";
    }
    else if (RegTime >= 7 && RegTime < 14)
    {
        StatusColor = "Image/yellow-4040.jpg";
    }
    else if (RegTime >= 14 && RegTime < 21)
    {
        StatusColor = "Image/orange-4040.jpg";
    }
    else
    {
        StatusColor = "Image/red-4040.jpg";
    }
    conn.Close();
    return StatusColor;
}

但问题是,当运行此代码时,只计算数据库中时差1的行,而对于其他行,则放置相同的RegTime,这会导致失败

c#两个日期之间的差异

通常,最好将这些值加载到GridView的DataSource中。这样就不必对每一行都再次访问数据库。

然而,根据DataReader的问题,您必须使用(while)-循环来循环DataReader中的所有行,如下所示:

public string DisplayWarning()
{
    using(var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RechnungConnectionString"].ConnectionString))
    using (var datecmd = new SqlCommand("Select DATEDIFF(day,Date,Getdate()) as DiffDate From Invoice", conn))
    {
        conn.Open();
        using (var reader = datecmd.ExecuteReader())
        {
            if (reader.HasRows){
                while (reader.Read())
                {
                    int regTime = reader.GetInt32(0);
                    string statusColor;
                    if (regTime < 7)
                    {
                        statusColor = "Image/green-4040.jpg";
                    }
                    else if (regTime >= 7 && regTime < 14)
                    {
                        statusColor = "Image/yellow-4040.jpg";
                    }
                    else if (regTime >= 14 && regTime < 21)
                    {
                        StatusColor = "Image/orange-4040.jpg";
                    }
                    else
                    {
                        statusColor = "Image/red-4040.jpg";
                    }
                    returnstatusColor;
                }
            }
            else{ 
                // output, log, exception ?!
            }
        }
    }
}

请注意,我还更改了一些其他内容,比如使用using-语句,这对于确保连接关闭(即使出现错误)总是一个好主意。

Update:但是您想为每一行调用此方法,那么您需要将行的键传递给this,这样您就可以将其作为参数传递给sql查询:

<asp:Image runat="server" ImageUrl='<%# DisplayWarning(System.Convert.ToInt32(Eval("InvoiceID"))) %>' Width="16" />     

Codebehin(假定密钥是int):

public string DisplayWarning(int invoiceID)
{
    string sql = @"Select DATEDIFF(day,Date,Getdate()) as DiffDate 
                   From Invoice 
                   WHERE InvoiceID=@InvoiceID";
    using(var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RechnungConnectionString"].ConnectionString))
    using (var datecmd = new SqlCommand(sql, conn))
    {
        datecmd.Parameters.Add(new SqlParameter("@InvoiceID", SqlDbType.Int)).Value = invoiceID;
        // Here you don't need a loop since you only get one row back
        // ...
    }
}

更新SqlDataSource1以将此计算作为结果集的一部分。除此之外,还可以使用sqlCASE语句来返回整个图像字符串。然后您可以将其直接绑定到图像控件。

在数据源中添加此属性怎么样?会是更清洁的解决方案。