Dig into the interchangeover between Unix timestamps and C DateTime time types

  • 2020-05-12 03:08:49
  • OfStack

The minimum unit of Unix time stamp is second and the starting time is 1970-01-01 00:00:00 GMT
The basic idea of the ConvertIntDateTime method is to represent the Unixk start time by getting the local time zone, plus the Unix time value (that is, the number of seconds in the past).
The basic idea of the ConvertDateTimeInt method is to convert the number of ticks into seconds by the difference in the number of ticks. Of course, what I'm returning here is the double type, which is not really the Unix timestamp format.
To get the real Unix timestamp, just get the integer part.

dangranusing System;
using System.Collections.Generic;
using System.Text;
namespace WWFramework.DateTimes
{
    /// <summary>
    ///  Time dependent function 
    /// </summary>
    public static class Function
    {
        /// <summary>
        ///  will Unix The timestamp is converted to DateTime The type of time 
        /// </summary>
        /// <param name="d">double  digital </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>
        ///  will c# DateTime Time format converted to Unix Timestamp format 
        /// </summary>
        /// <param name="time"> 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;
        }
    }
}


Related articles: