3

I need to get number of milliseconds from the epoch in GMT.

Can I use this for the GMT part:

DateTime.Now.ToUniversalTime()

What about the number of milliseconds since the epoch?

user489041
  • 27,916
  • 55
  • 135
  • 204
  • 3
    Not too much own research, eh? ;) possible duplicate of [Calculating Future Epoch Time in C#](http://stackoverflow.com/questions/906034/calculating-future-epoch-time-in-c-sharp) – bzlm Oct 27 '11 at 16:57

2 Answers2

8

This should give you a TimeZone agnostic answer.

TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1);
double ms = t.TotalMilliseconds ;
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Eoin Campbell
  • 43,500
  • 17
  • 101
  • 157
  • Wouldn't that second `DateTime` be local time, not UTC? – T.J. Crowder Aug 16 '17 at 12:26
  • Experimentation suggests that your code above is correct. Seeing that it's a bit counter-intuitive (one would think `new DateTime(1970, 1, 1)` would be local time and the calculation would be off), it would be useful to say *why* this works. – T.J. Crowder Aug 16 '17 at 13:10
0

You can do as easily as below in newer .NET versions;

DateTimeOffset.Now.ToUnixTimeMilliseconds()

Refer docs.

Irshad
  • 3,071
  • 5
  • 30
  • 51