How do you convert epoch time in C#?

后端 未结 14 2326
野的像风
野的像风 2020-11-22 06:51

How do you convert Unix epoch time into real time in C#? (Epoch beginning 1/1/1970)

14条回答
  •  失恋的感觉
    2020-11-22 07:04

    To not worry about using milliseconds or seconds just do:

        public static DateTime _ToDateTime(this long unixEpochTime)
        {
            DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var date = epoch.AddMilliseconds(unixEpochTime);
    
            if (date.Year > 1972)
                return date;
    
            return epoch.AddSeconds(unixEpochTime);
        }
    

    If epoch time is in seconds then there is no way you can pass year 1972 adding milliseconds.

提交回复
热议问题