C#中計算時間差中的小數(shù)問題解決
問題:
startTime = DateTime.Now;
-----------
slExecutedTime.Text = (DateTime.Now - startTime).ToString();
執(zhí)行結(jié)果:
已執(zhí)行:00:00:03.1234434(后面會多出很多的小數(shù)位)
想要的執(zhí)行結(jié)果:
已執(zhí)行:00:00:03
--------------------------------------------------------------------------------
解決方案一(推薦):
TimeSpan的相關(guān)屬性:
相關(guān)屬性和函數(shù)
Add:與另一個TimeSpan值相加。
Days:返回用天數(shù)計算的TimeSpan值。
Duration:獲取TimeSpan的絕對值。
Hours:返回用小時計算的TimeSpan值
Milliseconds:返回用毫秒計算的TimeSpan值。
Minutes:返回用分鐘計算的TimeSpan值。
Negate:返回當(dāng)前實(shí)例的相反數(shù)。
Seconds:返回用秒計算的TimeSpan值。
Subtract:從中減去另一個TimeSpan值。
Ticks:返回TimeSpan值的tick數(shù)。
TotalDays:返回TimeSpan值表示的天數(shù)。
TotalHours:返回TimeSpan值表示的小時數(shù)。
TotalMilliseconds:返回TimeSpan值表示的毫秒數(shù)。
TotalMinutes:返回TimeSpan值表示的分鐘數(shù)。
TotalSeconds:返回TimeSpan值表示的秒數(shù)。
/// <summary>
/// 程序執(zhí)行時間測試
/// </summary>
/// <param name="dateBegin">開始時間</param>
/// <param name="dateEnd">結(jié)束時間</param>
/// <returns>返回(秒)單位,比如: 0.00239秒</returns>
public static string ExecDateDiff(DateTime dateBegin, DateTime dateEnd)
{
TimeSpan ts1 = new TimeSpan(dateBegin.Ticks);
TimeSpan ts2 = new TimeSpan(dateEnd.Ticks);
TimeSpan ts3 = ts1.Subtract(ts2).Duration();
//你想轉(zhuǎn)的格式
return ts3.TotalMilliseconds.ToString();
}
這是最基本的,得到的是毫秒數(shù)
如果你是只單純的需要你的那種格式完全可以直接取前10位就行了
ts3.ToString("g") 0:00:07.171
ts3.ToString("c") 00:00:07.1710000
ts3.ToString("G") 0:00:00:07.1710000
有三種格式可以選擇,我建議如果需要其實(shí)一種的時候可以使用截取的試比較快捷
比如
ts3.ToString("g").Substring(0,8) 0:00:07.1
ts3.ToString("c").Substring(0,8) 00:00:07
ts3.ToString("G").Substring(0,8) 0:00:00
方案二:較繁瑣
#region 返回時間差
public static string DateDiff(DateTime DateTime1, DateTime DateTime2)
{
string dateDiff = null;
try
{
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
string hours = ts.Hours.ToString(), minutes = ts.Minutes.ToString(),seconds = ts.Seconds.ToString();
if(ts.Hours<10)
{
hours = "0" + ts.Hours.ToString();
}
if (ts.Minutes<10)
{
minutes = "0" + ts.Minutes.ToString();
}
if(ts.Seconds<10)
{
seconds = "0" + ts.Seconds.ToString();
}
dateDiff = hours + ":"+ minutes + ":"+ seconds;
}
catch
{
}
return dateDiff;
}
#endregion
來自:http://www.cnblogs.com/hongfei/archive/2013/03/11/2953366.html
相關(guān)文章
C#實(shí)現(xiàn)主窗體最小化后出現(xiàn)懸浮框及雙擊懸浮框恢復(fù)原窗體的方法
這篇文章主要介紹了C#實(shí)現(xiàn)主窗體最小化后出現(xiàn)懸浮框及雙擊懸浮框恢復(fù)原窗體的方法,涉及C#窗體及鼠標(biāo)事件響應(yīng)的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-08-08
C#實(shí)現(xiàn)遞歸調(diào)用的Lambda表達(dá)式
這篇文章介紹了C#實(shí)現(xiàn)遞歸調(diào)用的Lambda表達(dá)式,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06
c#之圓形無標(biāo)題欄橢圓窗體的實(shí)現(xiàn)詳解
本篇文章是對c#中圓形無標(biāo)題欄橢圓窗體的實(shí)現(xiàn)方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06

