本文實例講述了C#時間戳基本用法。分享給大家供大家參考。具體如下:
一、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(); } 經(jīng)常發(fā)現(xiàn)很多地方使用一個時間戳表示時間。比如: 1370838759 表示 2013年6月10日 12:32:39。 我們就需要一個工具,方便地轉(zhuǎn)換這種時間格式
二、什么是時間戳?
時間戳, 又叫Unix Stamp. 從1970年1月1日(UTC/GMT的午夜)開始所經(jīng)過的秒數(shù),不考慮閏秒。
三、C#時間戳轉(zhuǎn)換為普通時間
// 時間戳轉(zhuǎn)為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時間格式轉(zhuǎn)換為Unix時間戳格式private int DateTimeToStamp(System.DateTime time){  System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));  return (int)(time - startTime).TotalSeconds;}希望本文所述對大家的C#程序設(shè)計有所幫助。
新聞熱點
疑難解答
圖片精選