如何对日期进行算术运算?

编程入门 行业动态 更新时间:2024-10-09 15:18:29
本文介绍了如何对日期进行算术运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用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

更多推荐

如何对日期进行算术运算?

本文发布于:2023-11-30 15:46:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650565.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算术   日期

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!