如何对日期进行算术运算? [英] How to operate arithmetic operation on dates?

查看:93
本文介绍了如何对日期进行算术运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#.NET和SQL SERVER制作窗口应用程序.我有两个日期标签.开始日期和结束日期分别带有datetimepicker控件.现在我有第三个标签来计算日期之间的持续时间(差异) .我尝试了以下代码

I am making window application using C#.NET and SQL SERVER.I Have two labels in a form for dates.starting date and ending date with respective datetimepicker control.Now i have third label who computes the duration(difference)between dates.I have tried following code

private void txtduration_MouseClick(object sender, MouseEventArgs e)
      {
          int n;
          if (startingdate.Value > endingdate.Value)
          {
              n = Convert.ToInt32(startingdate.Value - endingdate.Value);
              txtduration.Text = n.ToString();
          }
          else
              n = Convert.ToInt32(endingdate.Value - startingdate.Value);
          txtduration.Text = n.ToString();
}



遇到错误
无法投射对象以键入"System.Timespan"以键入System.iconvertible

请就此帮我
提前感谢
问候



getting an error
Unable to cast object to type ''System.Timespan'' to type System.iconvertible

Please help me regarding this
Thanx in advance
regards

推荐答案

如果减去两个DateTime数据类型,则结果为TimeSpan.然后,您尝试将其转换为int,这是不可能的.根据您要尝试执行的操作,执行以下操作:

If you subtract two DateTime data types, then you get a TimeSpan as a result. You are then trying to convert this into an int, which is not possible. Depending on what you are trying to do you need do do this:

int n;
            if (startingdate.Value > endingdate.Value)
            {
                n = (int)(startingdate.Value - endingdate.Value).TotalSeconds;
                //n = (int)(startingdate.Value - endingdate.Value).TotalMinutes;
                //n = (int)(startingdate.Value - endingdate.Value).TotalDays; etc
                txtduration.Text = n.ToString();
            }
            else
                n = (int)(endingdate.Value - startingdate.Value).TotalSeconds;
            txtduration.Text = n.ToString();



假设您正在尝试以其中一种格式查找总时长

希望对您有帮助



This assumes you are trying to find the total duration in one of those formats

Hope this helps


这篇关于如何对日期进行算术运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆