public static string GetTimeStamp(System.DateTime time) //.net 2.0
{
long ts = ConvertDateTimeToInt(time);
return ts.ToString();
}
/// <summary>
/// 将c# DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name="time">时间</param>
/// <returns>long</returns>
public static long ConvertDateTimeToInt(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
long t = (time.Ticks - startTime.Ticks)/10000000 ; //除10000调整为10位
return t;
}
private DateTime GetDateTime(string timeStamp) //.net 2.0
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime;
if (timeStamp.Length == 10)
lTime = long.Parse(timeStamp + "0000000");
else
lTime = long.Parse(timeStamp + "0000");
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
public static long GetTimeStamp1(DateTime dateTime) //.net 3.5级以上
{
DateTime _dtStart = new DateTime(1970, 1, 1, 8, 0, 0);
//10位的时间戳
long timeStamp = Convert.ToInt32(dateTime.Subtract(_dtStart).TotalSeconds);
//13位的时间戳
//long timeStamp = Convert.ToInt64(dateTime.Subtract(_dtStart).TotalMilliseconds);
return timeStamp;
}
public static DateTime GetDateTime1(string timestamp) //.net 3.5级以上
{
System.DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
// long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
// DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
//使用上面的方式会显示TimeZone已过时
// DateTime dtStart = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);
long lTime;
if ( timestamp.Length ==10)
lTime = long.Parse(timestamp + "0000000");
else
lTime = long.Parse(timestamp + "0000");
TimeSpan timeSpan = new TimeSpan(lTime );
DateTime targetDt = dtStart.Add(timeSpan).AddHours(8);
return targetDt;
}