将时间格式转化为一个int类型
2014/1/14 13:01:26时间转完后为:1389675686数字
来源http://www.cnblogs.com/yc-755909659/archive/2012/12/25/2832673.html
为什么使用时间戳?
关于Unix时间戳,大概是这个意思,从1970年0时0分0秒开始到现在的秒数.使用它来获得的是一个INT值,储存在数据库里只要使用INT格式就可以了,方便数据库进行排序,搜索,而且比datetime格式更节省数据库空间。
以下是测试过的代码
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();
}