How To Convert DateTime To UnixTimeStamp in C#

How To Convert DateTime To UnixTimeStamp in C#

Unix time is the number of seconds since 1st January 1970, 00:00:00 UTC.

 

Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

 

using System;

namespace usingcsharp
{
    class Program
    {
        /* How to Convert DateTime To UnixTimeStamp in C# */
        static void Main(string[] args)
        {
            Console.Write("Unix Time Stamp: ");
            Console.WriteLine(ConvertDatetimeToUnixTimeStamp(DateTime.Now));

            Console.ReadKey();
        }
        public static long ConvertDatetimeToUnixTimeStamp(DateTime date)
        {
            DateTime originDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            TimeSpan diff = date.ToUniversalTime() - originDate;
            return (long)Math.Floor(diff.TotalSeconds);
        }
    }
}

 

public long UnixTimeNow()
{
    var timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
    return (long)timeSpan.TotalSeconds;
}

 

using System;

namespace usingcsharp
{
    class Program
    {
        /* How to Convert DateTime To UnixTimeStamp in C# */        
         /// provided in .Net 4.6
        /// In This Program, We will Convert Datetime
        /// To unixTimeStamp by using built in methods     
        
        static void Main(string[] args)
        {
            Console.Write("Unix Time Stamp: ");
            Console.WriteLine(ConvertDatetimeToUnixTimeStamp(DateTime.Now));

            Console.ReadKey();
        }

        public static long ConvertDatetimeToUnixTimeStamp(DateTime date)
        {
            var dateTimeOffset = new DateTimeOffset(date);
            var unixDateTime = dateTimeOffset.ToUnixTimeSeconds();
            return unixDateTime;
        }
    }
}

 

 

2021-10-03