C#时间戳和时间互转常用方法:
static readonly DateTime StartDateTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
/// <summary>
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp">13位整数型timestamp</param>
/// <returns></returns>
public static DateTime GetTime(long timeStamp)
{
try
{
TimeSpan toNow = new TimeSpan(timeStamp * 10000L);
return StartDateTime.Add(toNow);
}
catch
{
logger.Warn("时间戳转换失败", timeStamp.ToString());
return DateTime.Now;
}
}
/// <summary>
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp">13位整数型timestamp</param>
/// <returns></returns>
public static DateTime GetTime(string timeStamp)
{
if (string.IsNullOrEmpty(timeStamp)) { return DateTime.Now; }
try
{
long lTime = long.Parse(timeStamp) * 10000L;
TimeSpan toNow = new TimeSpan(lTime);
return StartDateTime.Add(toNow);
}
catch
{
logger.Warn("时间戳转换失败", timeStamp);
return DateTime.Now;
}
}
/// <summary>
/// DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name=”time”></param>
/// <returns></returns>
public static long ConvertDateTimeInt(DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (long)(time - startTime).Ticks / 10000;
}
希望以上分享对初学朋友有些帮助,谢谢!
更多关注付义方技术博客:http://blog.csdn.net/fuyifang
或者直接用手机扫描二维码查看更多博文: