C# 如何生成一個時間戳


 /// <summary>  
/// 獲取時間戳  
/// </summary>  
/// <returns></returns>  
public static string GetTimeStamp()  
{  
    TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);  
    return Convert.ToInt64(ts.TotalSeconds).ToString();  
}  

經常發現很多地方使用一個時間戳表示時間。比如: 1370838759  表示 2013年6月10日 12:32:39。 我們就需要一個工具,方便地轉換這種時間格式

 

什么是時間戳?

時間戳, 又叫Unix Stamp. 從1970年1月1日(UTC/GMT的午夜)開始所經過的秒數,不考慮閏秒。

 

C# 時間戳轉換為普通時間

// 時間戳轉為C#格式時間
        private DateTime StampToDateTime(string timeStamp)
        {
            DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime); 
            
            return dateTimeStart.Add(toNow);
        }

        // DateTime時間格式轉換為Unix時間戳格式
        private int DateTimeToStamp(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM