深入Unix時間戳與C# DateTime時間類型互換的詳解
更新時間:2013年06月05日 12:05:58 作者:
本篇文章是對Unix時間戳與C# DateTime時間類型互換進行了詳細的分析介紹,需要的朋友參考下
Unix時間戳最小單位是秒,開始時間為格林威治標準時間1970-01-01 00:00:00
ConvertIntDateTime方法的基本思路是通過獲取本地時區(qū)表示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;
}
}
}
ConvertIntDateTime方法的基本思路是通過獲取本地時區(qū)表示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;
}
}
}
相關文章
C#使用迭代器實現(xiàn)文字動態(tài)效果的示例代碼
這篇文章主要為大家詳細介紹了C#如何通過使用迭代器實現(xiàn)文字動態(tài)效果,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-02-02

