How To Convert DateTime To Unix TimeStamp in C#

How To Convert DateTime To Unix TimeStamp in C#

In this post, we will learn how to convert DateTime to UnixTimeStamp in C#.

Unix time is the number of seconds since 1 January 1970, 00:00:00 UTC. Before .Net 4.6, we used this way to convert Datetime To UnixTimeStamp as below:

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));

            //Hit ENTER to exit the program
            Console.ReadKey();
        }
        public static long ConvertDatetimeToUnixTimeStamp(DateTime date)
        {
            DateTime originDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            TimeSpan dif = date.ToUniversalTime() - originDate;
            return (long)Math.Floor(dif.TotalSeconds);
        }
    }
}

Another way

After, First, make sure you’re targeting the right version of the .NET Framework. Here is the method to convert to DateTime to UnixTimeStamp .NET 4.6, some new methods were added, but to use them, you will first have to convert from DateTime to DateTimeOffset as below:

using System;

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

            //Hit ENTER to exit the program
            Console.ReadKey();
        }

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

 

 

2021-10-03