How do you convert epoch time in C#?

后端 未结 14 2573
野的像风
野的像风 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:12

    If you are not using 4.6, this may help Source: System.IdentityModel.Tokens

        /// 
        /// DateTime as UTV for UnixEpoch
        /// 
        public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    
        /// 
        /// Per JWT spec:
        /// Gets the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the desired date/time.
        /// 
        /// The DateTime to convert to seconds.
        /// if dateTimeUtc less than UnixEpoch, return 0
        /// the number of seconds since Unix Epoch.
        public static long GetIntDate(DateTime datetime)
        {
            DateTime dateTimeUtc = datetime;
            if (datetime.Kind != DateTimeKind.Utc)
            {
                dateTimeUtc = datetime.ToUniversalTime();
            }
    
            if (dateTimeUtc.ToUniversalTime() <= UnixEpoch)
            {
                return 0;
            }
    
            return (long)(dateTimeUtc - UnixEpoch).TotalSeconds;
        }    
    

提交回复
热议问题