I'm assuming I should just parse the string into a DateTime and go from there... But is there a better way of doing this?
-
3What would constitute a "better way?" Why would you do it another way at all? Is there something specific you're trying to accomplish or determine? – gravity Jan 11 '19 at 15:33
-
Possible duplicate of [How to get the unix timestamp in C#](https://stackoverflow.com/questions/17632584/how-to-get-the-unix-timestamp-in-c-sharp) – Sinatr Jan 11 '19 at 15:39
3 Answers
You can use the DateTimeOffset
struct, which has a ToUnixTimeSeconds
(or ToUnixTimeMilliseconds
) method you can use:
long unixTimestamp = DateTimeOffset.Parse("2018-12-27T02:23:29").ToUnixTimeSeconds();
If you're curious how it's done, the source is here: https://referencesource.microsoft.com/#mscorlib/system/datetimeoffset.cs,8e1e87bf153c720e

- 36,127
- 5
- 30
- 43
You should parse it to a normal DateTime
object using something from the DateTime.Parse/ParseExact
family of functions, and then call a method like this:
public int ToUnixTime(DateTime d)
{
var epoch = new DateTime(1970,1,1);
return (int)(d - epoch).TotalSeconds;
}

- 399,467
- 113
- 570
- 794
DateTime interally stores the "Ticks" (a invented Time unit) since "12:00:00 midnight, January 1, 0001 (0:00:00 UTC on January 1, 0001), in the Gregorian calendar". As a Int64/Long Number. DateTime thus beats UnixTime easily in possible values. Converting to DateTime should be lossless.
Any ToString() call, any other Property call will simply calculate the values based on those Ticks (and culture/Timezone settings for ToString()). Everything else is just a interpretation of the Tick value.
You should parse to DateTime. And getting from Ticks to something as inprecise as the UnixTime is easy math. See Joels Answer for that.
Do note however the DateTimes preccision and accuaracy do not match fully: https://blogs.msdn.microsoft.com/ericlippert/2010/04/08/precision-and-accuracy-of-datetime/ DateTime.Now will usually give you only return values in 18 ms steps. And even the Stopwatch has issues with values < 1 ms.

- 9,634
- 2
- 17
- 31