I have had look around stackoverflow, and even looked at some of the suggested questions and none seem to answer, how do you get a unix timestamp in C#?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Truncating
.TotalSeconds
is important since it's defined asthe value of the current System.TimeSpan structure expressed in whole fractional seconds.
And how about an extension for
DateTime
? The second one is probably more confusing that it's worth until property extensions exist.I've spliced together the most elegant approaches to this utility method:
This is what I use.
You can also use Ticks. I'm coding for Windows Mobile so don't have the full set of methods. TotalSeconds is not available to me.
or
As of .NET 4.6, there is
DateTimeOffset.ToUnixTimeSeconds()
.This is an instance method, so you are expected to call it on an instance of
DateTimeOffset
. You can also cast any instance ofDateTime
, though beware the timezone.To get the current timestamp:
To get the timestamp from a
DateTime
:When you subtract 1970 from the current time, be aware that the timespan will most often have a non zero milliseconds field. If for some reason you are interested in the milliseconds, keep this in mind.
Here's what I did to get around this issue.