Unix时间戳与C# DateTime时间类型互换
/// <summary> /// method for converting a UNIX timestamp to a regular /// System.DateTime value (and also to the current local time) /// </summary> /// <param name="timestamp">value to be converted</param> /// <returns>converted DateTime in string format</returns> private static DateTime ConvertTimestamp(double timestamp) { //create a new DateTime value based on the Unix Epoch DateTime converted = new DateTime(1970, 1, 1, 0, 0, 0, 0); //add the timestamp to the value DateTime newDateTime = converted.AddSeconds(timestamp); //return the value in string format return newDateTime.ToLocalTime(); }
/// <summary> /// method for converting a System.DateTime value to a UNIX Timestamp /// </summary> /// <param name="value">date to convert</param> /// <returns></returns> private double ConvertToTimestamp(DateTime value) { //create Timespan by subtracting the value provided from //the Unix Epoch TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime()); //return the total seconds (which is a UNIX timestamp) return (double)span.TotalSeconds; }