;

How To Convert UnixTimeStamp to DateTime in C#


Tutorialsrack 01/03/2020 C# Programs

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

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

Code
using System;

namespace Tutorialsrack
{
    class Program
    {
        /* How to Convert UnixTimeStamp To DateTime in C# */
        static void Main(string[] args)
        {
            Console.Write("DateTime Convert From UnixTimeStamp: ");
            Console.WriteLine(ConvertUnixTimeStampToDateTime(1583077443));

            //Hit ENTER to exit the program
            Console.ReadKey();
        }
        public static DateTime ConvertUnixTimeStampToDateTime(long unixtime)
        {
            DateTime sTime = new DateTime(1970, 1, 1, 0, 0, 0).ToLocalTime();
            return sTime.AddSeconds(unixtime);
        }
    }
}

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

Code
using System;

namespace Tutorialsrack
{
    class Program
    {
        /* How to Convert UnixTimeStamp To DateTime in C# */
        ///
        /// In This Program, We will Convert UnixTimeStamp
        /// To DateTime by using built in methods 
        /// provided in .Net 4.6 
        /// 
        ///
        static void Main(string[] args)
        {
            Console.Write("DateTime Convert From UnixTimeStamp: ");
            Console.WriteLine(ConvertUnixTimeStampToDateTime(1583077443));

            //Hit ENTER to exit the program
            Console.ReadKey();
        }
        public static DateTime ConvertUnixTimeStampToDateTime(long unixtime)
        {
            var localDateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(unixtime).DateTime.ToLocalTime();
            return localDateTimeOffset;
        }
    }
}

I hope this article will help you to understand how to convert UnixTimeStamp to DateTime in C#.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags