c# datetime與 timeStamp時間戳 互相轉換


將時間格式轉化為一個int類型  
2014/1/14 13:01:26時間轉完后為:1389675686數字  

為什么使用時間戳?

關於Unix時間戳,大概是這個意思,從1970年0時0分0秒開始到現在的秒數.使用它來獲得的是一個INT值,儲存在數據庫里只要使用INT格式就可以了,方便數據庫進行排序,搜索,而且比datetime格式更節省數據庫空間。

正式使用的代碼,獲得毫秒數:

/// <summary>
/// 生成時間戳 
/// </summary>
/// <returns>當前時間減去 1970-01-01 00.00.00 得到的毫秒數</returns>
public string GetTimeStamp()
{
    DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
    DateTime nowTime = DateTime.Now;
    long unixTime = (long)System.Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero);
    return unixTime.ToString();
}

 

以下為 他人 博客代碼:

以下是測試過的代碼

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  
  
namespace test.Controllers  
{  
    public class TimeStampController : Controller  
    {  
        //  
        // GET: /TimeStamp/  
  
        public ActionResult Index()  
        {  
            ViewBag.TimeStamp = ConvertDateTimeInt(DateTime.Now);  
            return View("TimeStamp");  
        }  
  
        public ActionResult GetTimeView(string timeStamp)  
        {  
            ViewBag.TimeStamp = GetTime(timeStamp);  
            return View("TimeStamp");  
        }  
  
        /// <summary>  
        /// 時間戳轉為C#格式時間  
        /// </summary>  
        /// <param name="timeStamp">Unix時間戳格式</param>  
        /// <returns>C#格式時間</returns>  
        public static DateTime GetTime(string timeStamp)  
        {  
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));  
            long lTime = long.Parse(timeStamp + "0000000");  
            TimeSpan toNow = new TimeSpan(lTime);  
            return dtStart.Add(toNow);  
        }  
  
  
        /// <summary>  
        /// DateTime時間格式轉換為Unix時間戳格式  
        /// </summary>  
        /// <param name="time"> DateTime時間格式</param>  
        /// <returns>Unix時間戳格式</returns>  
        public static int ConvertDateTimeInt(System.DateTime time)  
        {  
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));  
            return (int)(time - startTime).TotalSeconds;  
        }  
  
    }  
}  

double格式存儲

static double ToTimestamp(DateTime value)  
{  
    TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());  
    return (double)span.TotalSeconds;  
}  
  
static DateTime ConvertTimestamp(double timestamp)  
{  
    DateTime converted = new DateTime(1970, 1, 1, 0, 0, 0, 0);  
    DateTime newDateTime = converted.AddSeconds(timestamp);  
    return newDateTime.ToLocalTime();  
}  

 

參考:18妹的小窩     c# datetime與 timeStamp 互相轉換

 


免責聲明!

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



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