Unix时间戳最小单位是秒,开始时间为格林威治标准时间1970-01-01 00:00:00
ConvertIntDateTime方法的基本思路是通过获取本地时区表示Unixk开始时间,加上Unix时间值(即过去的秒数).
ConvertDateTimeInt方法的基本思路是通过刻度数差,再把刻度数转换为秒数,当然要说明的是,我这里返回的是double类型,意义上并非是真正的Unix时间戳格式。
要获取真正Unix时间戳的,只获取整数部分就可以了。
dangranusing System;
using System.Collections.Generic;
using System.Text;
namespace WWFramework.DateTimes
{
/// <summary>
/// 时间相关函数
/// </summary>
public static class Function
{
/// <summary>
/// 将Unix时间戳转换为DateTime类型时间
/// </summary>
/// <param name="d">double 型数字</param>
/// <returns>DateTime</returns>
public static System.DateTime ConvertIntDateTime(double d)
{
System.DateTime time = System.DateTime.MinValue;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
time = startTime.AddSeconds(d);
return time;
}
/// <summary>
/// 将c# DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name="time">时间</param>
/// <returns>double</returns>
public static double ConvertDateTimeInt(System.DateTime time)
{
double intResult = 0;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
intResult = (time - startTime).TotalSeconds;
return intResult;
}
}
}
using System.Collections.Generic;
using System.Text;
namespace WWFramework.DateTimes
{
/// <summary>
/// 时间相关函数
/// </summary>
public static class Function
{
/// <summary>
/// 将Unix时间戳转换为DateTime类型时间
/// </summary>
/// <param name="d">double 型数字</param>
/// <returns>DateTime</returns>
public static System.DateTime ConvertIntDateTime(double d)
{
System.DateTime time = System.DateTime.MinValue;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
time = startTime.AddSeconds(d);
return time;
}
/// <summary>
/// 将c# DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name="time">时间</param>
/// <returns>double</returns>
public static double ConvertDateTimeInt(System.DateTime time)
{
double intResult = 0;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
intResult = (time - startTime).TotalSeconds;
return intResult;
}
}
}