In this article, we will see a simple approach to how to convert UNIX Epoch time to DateTime – C# .NET and then convert the regular date to UNIX format using C# code.
Today in this article, we will cover below aspects,
.NET and .NET Core have provided inbuilt support to transform the Dates to and from Unix Time represented by either seconds or milliseconds.
I have a timestamp which is a Unix timestamp that I would be converting to
C# – UNIX Epoch time to Date time
Example
Date Value: ‘151984000000‘
Let’s convert the above value to Readable format using C#.
DateTimeOffset dateTimeOffSet = DateTimeOffset.FromUnixTimeMilliseconds(1581984000000);
DateTime dateTime = dateTimeOffSet.DateTime;
The above code converts the ‘151984000000‘ date as ‘2/18/2020 12:00:00 AM’
Unix time in seconds
If you need to use Unix time in seconds please code as below,
DateTimeOffset dateTimeOffSet = DateTimeOffset.FromUnixTimeSeconds(time);
DateTime datTime = dateTimeOffSet.DateTime
C# – Convert Date to Unix Epoch Date
If you have any regular date fields as shown below,
Example
Date – ‘2/18/2019 12:00:00 AM’
We can convert regular dates to UNIX format as below using C# code as below,
DateTimeOffset dateTimeOffSet = DateTimeOffset.Parse("2/18/2019 12:00:00 AM");
long date = dateTimeOffSet.ToUnixTimeMilliseconds();
Above we are transforming the dates to Unix epoch format,
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.
Your code is giving me a 1974 Year for a timestamp created in 2019
Hi itdontwork- I hope you are using correct method for second and millisecond. could you please share an example ?