常用的几个DateTime处理方法

常用的几个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;
    }
}

 

你可能感兴趣的:(DateTime)