よく使われるいくつかのDateTime処理方法

2506 ワード

よく使われるいくつかのDateTime処理方法
using System;
using System.Collections.Generic;


class TimeUtil
{
    static DateTime timeStamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);  // 1970   
    /// <summary>
    ///  1970/1/1 
    /// </summary>
    /// <returns></returns>
    public static int GetNowUnixTicks()
    {
        TimeSpan span = System.DateTime.UtcNow - timeStamp;
        return (int)span.TotalSeconds;
    }
    // 
    public static string GetTimeDurationSoFar(int happenTime)
    {
        int duration = GetNowUnixTicks() - happenTime;
        if (duration > 0)
        {
            if (duration < 5 * 60) return " ";
            if (duration < 60 * 60) return (int)(duration / 60) + " ";
            if (duration < 24 * 60 * 60) return (int)(duration / 60 / 60) + " ";
            if (duration < 30 * 24 * 60 * 60) return (int)(duration / 60 / 60 / 24) + " ";
            return (int)(duration / 60 / 60 / 24 / 30) + " ";
        }
        else
        {
            return " ";
        }
    }
    /// <summary>
    ///  Unix DateTime 
    /// </summary>
    /// <param name="d">int  </param>
    /// <returns>DateTime</returns>
    public static System.DateTime ConvertIntDateTime(int d)
    {
        System.DateTime time = System.DateTime.MinValue;
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
        time = startTime.AddSeconds(d);
        return time;
	// 
	//return timeStamp.AddSeconds(d);
    }

    /// <summary>
    ///  c# DateTime Unix 
    /// </summary>
    /// <param name="time"> </param>
    /// <returns>int</returns>
    public static int ConvertDateTimeInt(System.DateTime time)
    {
        int intResult = 0;
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
        intResult = (int)(time - startTime).TotalSeconds;
        return intResult;
	// 
	//return (int)(time - timeStamp).TotalSeconds;
    }
}