如何计算两个不同日期和时间之间的差异 [英] how to calculate difference between two different date and time
本文介绍了如何计算两个不同日期和时间之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用c#知道asp.net中的代码.
假设我们有两个日期时间为:
a)21/09/2011 12:35
b)2011年10月17日17:54
那么我想计算它们之间的差异为:
(_)个月(_)天(_)小时(_)分钟
或作为
(_)天(_)小时(_)分钟
Hi,
i like to know the code in asp.net using c#.
suppose we have two datetime as:
a) 21/09/2011 12:35
b) 17/10/2011 17:54
then i want to calculate difference between them as:
(_)months (_)days (_)hours (_) minutes
or as
(_)days (_)hours (_) minutes
推荐答案
使用TimeSpan类获得差异非常容易.
it is very easy use TimeSpan class to get difference.
//first convert you dates to DateTime object
DateTime dt1 =Convert.ToDateTime("21/09/2011 12:35");
DateTime dt2 =Convert.ToDateTime("17/10/2011 17:54");
TimeSpan objTimeSpan = dt2-dt1;
int days = objTimeSpan.Days;
int hours = objTimeSpan.Hours;
int Min = objTimeSpan.Minutes;
int sec = objTimeSpan.Seconds;
MessageBox.Show("days:"+days.ToString() + " hours:"+hours.ToString() + " min:"+Min.ToString() + " secs:"+sec.ToString());
[Edit]将字符串转换为日期时间并添加显示消息[/Edit] -Uday
string is converted to datetime and display message is added[/Edit] -Uday
使用TImeSpan
类始终是一个不错的选择.
在此处 [ ^ ].这将在使用TimeSpan
类时回答您的问题.
Using theTImeSpan
class is always a good option.
Have a look here[^]. This will answer your question while using theTimeSpan
class.
datetimeB.Subtract(datetimeA).TotalSeconds,.TotalMinutes,.TotalHours
datetimeB.Subtract(datetimeA).TotalSeconds , .TotalMinutes , .TotalHours
这篇关于如何计算两个不同日期和时间之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文