如何使用DateTimePicker(shortime)计算两次之间的时间? [英] how to calculate the time between two times using DateTimePicker (shortime) ?

查看:72
本文介绍了如何使用DateTimePicker(shortime)计算两次之间的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试计算时遇到麻烦(例如晚上11点到凌晨1点)

i得到的总时数为-21而不是2,所以我很困惑

这是我的代码:

i face trouble when i try to calculate for example (11:00 PM to 1:00 AM)
i get the total of hours -21 instead of 2, so iam confused
this is my code:

DateTime date1 =
    System.Convert.ToDateTime(DTimeBeginWork.Value);
DateTime date2 =
    System.Convert.ToDateTime(DTimeEndWork.Value);


TimeSpan ts = new TimeSpan();
ts = date2.Subtract(date1);
DgNHours.DigitText = (ts.Hours.ToString());
DgNMinutes.DigitText = (ts.Minutes.ToString());

推荐答案

使用自然为 System.DateTime <自然定义的' - '运算符更清晰/ code>,如

It's much cleaner to use '-' operator naturally defined for System.DateTime, as in
TimeSpan ts = date2 - date1;



此表格将不要在标志上留下歧义的空间,但你可以获得正面或负面的时间跨度,具体取决于什么时候更早。



并且,确切的时间间隔(时间跨度),使用非混淆 TotalHours 属性,而不是小时,或其他总计* 的属性System.TimeSpan

http://msdn.microsoft.com/en-us/library/system.timespan.aspx [ ^ ]。



-SA


This form would not leave a room for ambiguity in sign, but you can get either positive or negative time span, depending on what time is sooner.

And, for exact time interval (time span), use non-confusing TotalHours property, instead of Hours, or other Total* properties of System.TimeSpan:
http://msdn.microsoft.com/en-us/library/system.timespan.aspx[^].

—SA


DateTime date1 = System.Convert.ToDateTime(DTimeBeginWork.Value);
DateTime date2 = System.Convert.ToDateTime(DTimeEndWork.Value);

string date1String = date1.ToString("dd-MM-yyyy hh:mm:ss tt"); 
string date2String = date2.ToString("dd-MM-yyyy hh:mm:ss tt");
 
TimeSpan ts = new TimeSpan();
ts = date2.Subtract(date1);
DgNHours.DigitText = (ts.TotalHours.ToString());
DgNMinutes.DigitText = (ts.Minutes.ToString());





在你的代码中我添加了两个用于显示的语句date1和date2也将ts.Hours更改为ts.TotalHours。根据你的例子,如果你通过(晚上11点到凌晨1点),这段代码将返回-22。

这是正确的,因为如果你检查date1String和date2String它将是03-07- 2013 11:00:00 PM

和03-07-2013 01:00:00 AM(按照今天的日期),这些日期之间的差异将为-22。



如果您将值传递给03-07-2013 11:00:00 PM到04-07-2013 01:00:00 AM那么它将返回2作为结果。所以你必须传递日期和时间值才能得到正确的结果。



In your code I added two statements for displaying date1 and date2 also changed the ts.Hours to ts.TotalHours. As per your example if you pass (11:00 PM to 1:00 AM) this code will return -22.
That is correct because if you check date1String and date2String it will be 03-07-2013 11:00:00 PM
and 03-07-2013 01:00:00 AM respectively ( as per today's date), the difference between these date will be -22.

If you pass the values as 03-07-2013 11:00:00 PM to 04-07-2013 01:00:00 AM then it will return 2 as result.So you have to pass the date along with the time value to get the proper result.


这篇关于如何使用DateTimePicker(shortime)计算两次之间的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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