Convert C# DateTime Object To A Unix Timestamp

Visual C#

Quite often when dealing with an API or some other external service, you will find that you get Unix timestamps returned to you or alternatively have to provide a timestamp in Unix form when sending a request back. Since you are going to be running your .NET code on a windows machine, you don’t have a built in way to get the time in Unix format. It is pretty simple to obtain a Unix timestamp though.┬áHere is what you need to do to convert C# DateTime object to a Unix timestamp.

The following helper method can be used to convert a standard datetime object into a Unix timestamp value. The value is quite large and will get bigger as time goes on, so make sure to use an appropriate variable type. Long will work fine for this scenario.

It’s a pretty simple method with little to explain. Its worth noting that you need to keep this as a long. Int is not going to be big enough to hold the time value.

If you want to do things in reverse. I.e. Convert a Unix timestamp back to a C# DateTime object, you can use the following helper method.

 

Leave a Reply

Your email address will not be published. Required fields are marked *