timespan使用方法详解


几点重要的用法:

a 先来介绍几个方法

TimeSpan.Minutes(其他时间比如天数,小时数,秒数都一样的情况下得到的分钟数的差),其他的Hours,Second一样
DateTime.Tick :是一个计时周期,表示一百纳秒,即一千万分之一秒,那么 Ticks 在这里表示总共相差多少个时间周期,即:9 * 24 *                    3600 * 10000000 + 23 * 3600 * 10000000 + 59 * 60 * 10000000 + 59 * 10000000 = 8639990000000。3600 是一小时                    的秒数
TimeSpan.TotalDays:两个时间段相差的日数,其他的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:就表示两个时间相差的分钟数,上面的例子就是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
    }
}


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3