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.
public static long ConvertToUnixTime(DateTime datetime) { DateTime sTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return (long)(datetime - sTime).TotalSeconds; }
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.
public static DateTime UnixTimeToDateTime(long unixtime) { DateTime sTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return sTime.AddSeconds(unixtime); }