如何在C#中计算2个不同日期之间的小时数

编程入门 行业动态 更新时间:2024-10-16 16:30:23
本文介绍了如何在C#中计算2个不同日期之间的小时数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在构建一个程序,在该程序中我需要计算不同日期之间的差.......它是一个网络中断程序,我想计算不同日期之间的停机时间,例如,网络在2013年6月6日停机9:00 AM,并于09/06/2013 10:00 PM恢复。...停机时间应为34小时.........我已经能够计算出天数,但是我希望小时格式,所以任何人都可以帮助我........ im使用datetimePicker来获取日期和时间。

I have been building a program where i need to calculate the difference between different dates....... its a network outage program i want to calculate down time between different dates e.g network was down on 08/06/2013 9:00 AM and was restored on 09/06/2013 10:00 PM.... the down time should be 34 hours......... i have been able to calculate the days but i want this in hour format so anyone please help me............. i m using datetimePicker to get the date and time at the same time.

我为此目的一直使用下面提到的代码

i have been using the below mentioned code for that purpose

dateTimePicker1.Format = DateTimePickerFormat.Custom; dateTimePicker1.CustomFormat = " dd/MM/yyyy hh:mm tt "; dateTimePicker2.Format = DateTimePickerFormat.Custom; dateTimePicker2.CustomFormat = " dd/MM/yyyy hh:mm tt "; ts1 = dt2.Subtract(dt1); richTextBox1.Text = "The Hours Difference is:\t" + dt2.Subtract(dt1).Hours + "\n The Minute Difference is:\t" + dt2.Subtract(dt1).Minutes;

推荐答案

您可以使用.Net时间跨度类。

You can use the .Net timespan class for this.

System.DateTime firstDate = new System.DateTime(2006, 9, 13, 12, 0, 0); System.DateTime SecondDate = new System.DateTime(2006, 9, 13, 0, 0, 0); System.TimeSpan diffResult = firstDate.Subtract(SecondDate);

diffResult 将包含 firstDate 和 secondDate 在年,月,日,小时,分钟和秒。

diffResult will contain all the differences in firstDate and secondDate in year, month, day, hour, minutes and seconds.

您可以从中获取任何日期部分:

You can get any datepart from this:

diffResult.Days diffResult.Hours diffResult.Minutes etc.

更多推荐

如何在C#中计算2个不同日期之间的小时数

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

发布评论

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

>www.elefans.com

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