在C#中获取两次之间的小时数 [英] Get the number of hours between two time in C#
本文介绍了在C#中获取两次之间的小时数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
伙计们,您能举个例子吗?我想获取两次时间之间的小时数,例如t1 = 10:00AM和t2 = 12:00PM,因此t3 = 2 ???
非常感谢=>
guys could you give me some example to this i want to get the numbers of hours between two time like t1=10:00AM and t2=12:00PM therefore t3=2???
thanks a lot =>
推荐答案
DateTime dFrom;
DateTime dTo;
string sDateFrom = "11:56:00";
string sDateTo = "12:12:00";
if (DateTime.TryParse(sDateFrom, out dFrom) && DateTime.TryParse(sDateTo, out dTo))
{
TimeSpan TS = dTo - dFrom;
int hour = TS.Hours;
int mins = TS.Minutes;
int secs = TS.Seconds;
string timeDiff = hour.ToString("00") + ":" + mins.ToString("00") + ":" + secs.ToString("00");
Response.Write(timeDiff); //output 16 mins in format 00:16:00
}
给出,
Given,
t1=10:00 AM<br />
t2=12:00 PM
要计算小时差:
To Calculate difference in hours:
DateTime dtFrom = DateTime.Parse("10:00 AM");
DateTime dtTo = DateTime.Parse("12:00 PM");
int timeDiff = dtFrom.Value.Subtract(dtTo.Value).Hours;
timeDiff是您所需的小时数差异
timeDiff is the difference in hours you require
TimeSpan timeSpan1 = new TimeSpan(10, 0, 0);
TimeSpan timeSpan2 = new TimeSpan(12, 0, 0);
var timeDiff = timeSpan2.Subtract(timeSpan1);
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, timeDiff.Hours, timeDiff.Minutes, timeDiff.Seconds, DateTimeKind.Local);
这篇关于在C#中获取两次之间的小时数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文