欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

timespan使用方法詳解

 更新時間:2014年04月09日 09:49:41   作者:  
TimeSpan是用來表示一個時間段的實例,兩個時間的差可以構成一個TimeSpan實例,現(xiàn)在就來介紹一下使用方法

幾點重要的用法:

a 先來介紹幾個方法

TimeSpan.Minutes(其他時間比如天數(shù),小時數(shù),秒數(shù)都一樣的情況下得到的分鐘數(shù)的差),其他的Hours,Second一樣
DateTime.Tick :是一個計時周期,表示一百納秒,即一千萬分之一秒,那么 Ticks 在這里表示總共相差多少個時間周期,即:9 * 24 *                    3600 * 10000000 + 23 * 3600 * 10000000 + 59 * 60 * 10000000 + 59 * 10000000 = 8639990000000。3600 是一小時                    的秒數(shù)
TimeSpan.TotalDays:兩個時間段相差的日數(shù),其他的TotalHours,TotalMinutes,TotalSeconds 一樣

b 兩個時間的差

復制代碼 代碼如下:

string time1 = "2010-5-26 8:10:00";
string time2 = "2010-5-26 18:20:00";
DateTime t1 = Convert.ToDateTime(time1);
DateTime t2 = Convert.ToDateTime(time2);

TimeSpan ts1=t2-t1;
string tsMin=ts1.Minutes.ToString();

 
TimeSpan ts11=new TimeSpan(t1.Tick);
TimeSpan ts22=new TimeSpan(t2.Tick);

string diff=ts22.Subtract(ts11).TotalMinutes.ToString();

Subtract:表示兩個時間段的差
diff:就表示兩個時間相差的分鐘數(shù),上面的例子就是610分鐘。

 得到一個 TimeSpan 實例,TimeSpan 有一些屬性:Days、TotalDays、Hours、TotalHours、Minutes、TotalMinutes、Seconds、TotalSeconds、Ticks,注意沒有 TotalTicks。
這些屬性名稱開始理解有些困難,但閱讀本文后,相應您一定茅塞頓開。

舉例說明

時間 1 是 2010-1-2 8:43:35;
時間 2 是 2010-1-12 8:43:34。
用時間 2 減時間 1,得到一個 TimeSpan 實例。

那么時間 2 比時間 1 多 9 天 23 小時 59 分 59 秒。

那么,Days 就是 9,Hours 就是 23,Minutes 就是 59,Seconds 就是 59。

所以以后想知道兩個時間段的差就容易的多了

TimeSpan Format Helper

復制代碼 代碼如下:

using System;
using System.Collections.Generic;

class TimeSpanUtility
{
    public static string FormatString(TimeSpan aTimeSpan)
    {
        string newFormat = aTimeSpan.ToString("d'd 'h'h 'm'm 's's'");
        // 1d 3h 43m 23s

        return newFormat;
    }

    public static string TimeSpanInWords(TimeSpan aTimeSpan)
    {
        List<string> timeStrings = new List<string>();

        int[] timeParts = new[] { aTimeSpan.Days, aTimeSpan.Hours, aTimeSpan.Minutes, aTimeSpan.Seconds };
        string[] timeUnits = new[] { "day", "hour", "minute", "second" };

        for (int i = 0; i < timeParts.Length; i++)
        {
            if (timeParts[i] > 0)
            {
                timeStrings.Add(string.Format("{0} {1}", timeParts[i], Pluralize(timeParts[i], timeUnits[i])));
            }
        }

        return timeStrings.Count != 0 ? string.Join(", ", timeStrings.ToArray()) : "0 seconds";
    }

    private static string Pluralize(int n, string unit)
    {
        if (string.IsNullOrEmpty(unit)) return string.Empty;

        n = Math.Abs(n); // -1 should be singular, too

        return unit + (n == 1 ? string.Empty : "s");
    }
}

public class Client
{
    static void Main()
    {
        // 12 days, 23 hours, 24 minutes, 2 seconds.
        TimeSpan span = new TimeSpan(12, 23, 24, 2);

        Console.WriteLine(TimeSpanUtility.TimeSpanInWords(span));   // Output: 12 days, 23 hours, 24 minutes, 2 seconds
        Console.WriteLine(TimeSpanUtility.FormatString(span));  // Output: 12d 23h 24m 2s
    }
}

相關文章

最新評論