将TimeSpan转换为Int

时间:2017-11-19 13:00:17

标签: c# asp.net casting int timespan

我有一个Vacation表,其中包含以下三列:

平衡varchar(20), National_ID varchar(15), NoOfDays varchar(20),

我使用此代码更新表值:

protected void btnadd_Click(object sender, EventArgs e)
    {
        TimeSpan remaindate;
        DateTime start = DateTime.Parse(tbstartvaca.Text).Date;
        DateTime end = DateTime.Parse(tbendvaca.Text).Date;
        TimeSpan vacation = TimeSpan.Parse(lbldays.Text);
        TimeSpan total;
        if (start > end)
        {
            lberr.Text = "Please check again on Starting date";
            return;
        }
        else
        {
            remaindate = end - start;
            lberr.Text = "you have left with " + remaindate.TotalDays + "days.";
            total = vacation - remaindate;
            lbldays.Text = "you have left with " + total.TotalDays + "days.";
            s = "Update Vacation set Balance = '" + total + "', NoOfDays ='" + remaindate + "' where National_ID = '" + lblid.Text+ "'";
            if (db.Run(s))
            {
                //lberr.Text = "The data has update";
            }

            else
            {
                lberr.Text = "The data has not update";
            }
        }

    }

如何使用变量和总计算后的公式将数据类型从TimeSpan更改为integer,以便将表中的值保存为int?

请注意,我使用Balance和NoOfDays将值类型更改为varchar(20)以使项目正常工作。

3 个答案:

答案 0 :(得分:0)

如果您从.net获取特定值,那么您将得到一个int。 比如天。你想要什么时间跨度?

例如:

TimeSpan g = TimeSpan.MinValue;
int p = g.Days;

*在您的代码中,您似乎理解了这个概念。 我认为您无法将Timespan转换为Integer。

请编辑您的问题,以便我们更好地理解*

答案 1 :(得分:0)

尝试将您的数据库查询更改为: "Update Vacation set Balance = " + total.TotalDays + ", NoOfDays = " + remaindate.TotalDays + " where National_ID = '" + lblid.Text + "'"

答案 2 :(得分:0)

首先,我建议将Balance和NoOfDays类型设置回int。它只会给你的程序增加不必要的复杂性,用于字符串解析,浪费空间等......

对于你的问题,最简单的事情(正如其他人建议的那样)就是直接将total变量转换为int:

int days = (int)total.TotalDays;