C# TimeSpan實現對時間差的計算

直接上代碼:)code

var acc= entities.AccountLoginInfoes.Where(r => r.AccountID == item.DevID&&r.AccountType==0).ToList();
               TimeSpan time = new TimeSpan();
               string dateDiff = null;
                
                foreach (var i in acc)
                {
                    if (!string.IsNullOrWhiteSpace(i.LoginTime)&&!string.IsNullOrWhiteSpace(i.LogoutTime))//LoginTime登錄時間  LogoutTime登出時間
                    {
                        
                        var in1 = Convert.ToDateTime(i.LogoutTime);
                        var out1 = Convert.ToDateTime(i.LoginTime);
                        time += in1 - out1;

                        TimeSpan ts1 = new TimeSpan(in1.Ticks);
                        TimeSpan ts2 = new TimeSpan(out1.Ticks);

                        TimeSpan ts = ts1.Subtract(ts2).Duration();
                        string days = ts.Days.ToString(), hours = ts.Hours.ToString(), minutes = ts.Minutes.ToString(), seconds = ts.Seconds.ToString();

                        if (ts.Days < 10)
                            {
                                days = "0" + ts.Days.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 = days + "天" + hours + "時" + minutes + "分" + seconds + "秒";

                        }
                   
                }

最後的顯示效果blog

補充:string

TimeSpan 結構  表示一個時間間隔。it

命名空間:System 程序集:mscorlib(在 mscorlib.dll 中)io

說明: 1.DateTime值類型表明了一個從公元0001年1月1日0點0分0秒到公元9999年12月31日23點59分59秒之間的具體日期時刻。所以,你能夠用DateTime值類型來描述任何在想象範圍以內的時間。TimeSpan值包含了許多屬性與方法,用於訪問或處理一個TimeSpan值,class

其中的五個重載方法之一的結構 TimeSpan( int days, int hours, int minutes, int seconds )date

下面的列表涵蓋了其中的一部分方法及屬性解釋foreach

Add:與另外一個TimeSpan值相加。List

Days:返回用天數計算的TimeSpan值。命名空間

Duration:獲取TimeSpan的絕對值。

Hours:返回用小時計算的TimeSpan值

Milliseconds:返回用毫秒計算的TimeSpan值。

Minutes:返回用分鐘計算的TimeSpan值。

Negate:返回當前實例的相反數。

Seconds:返回用秒計算的TimeSpan值。

Subtract:從中減去另外一個TimeSpan值。

Ticks:返回TimeSpan值的tick數。

TotalDays:返回TimeSpan值表示的天數。

TotalHours:返回TimeSpan值表示的小時數。

TotalMilliseconds:返回TimeSpan值表示的毫秒數。

TotalMinutes:返回TimeSpan值表示的分鐘數。

TotalSeconds:返回TimeSpan值表示的秒數。

相關文章
相關標籤/搜索