0

I need to store dates in a form of number of seconds since 1970.

With this I am getting number of seconds since 1970 with Swift by using Foundation's NSDate:

NSDate().timeIntervalSince1970

And maybe a dumb question but why this is double shouldn't it be int?

What is equivalent of this method in C#?

I am not sure what to use to get the same value.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
1110
  • 7,829
  • 55
  • 176
  • 334

2 Answers2

3
TimeSpan t = (DateTime.UtcNow – new DateTime(1970, 1, 1));
long timestamp  = (long) t.TotalSeconds;

I used the UtcNow property to ensure that the timestamp is the same regardless of what timezone this code is being run in.

Also, use the largest integer type you can find since the current epoch time is slightly less than 32 bit signed integer and you want code to be future proof.

If you do have .NET 4.6 or above, try this:

 DateTimeOffset.UtcNow.ToUnixTimeSeconds() 
Matthew Strawbridge
  • 19,940
  • 10
  • 72
  • 93
Ashhar Hasan
  • 803
  • 14
  • 34
  • Is swift NSDate().timeIntervalSince1970; also UTC based? – 1110 Jan 06 '17 at 11:26
  • Yes. It is UTC too. See https://developer.apple.com/reference/foundation/nsdate/1416453-init – Ashhar Hasan Jan 06 '17 at 11:28
  • Tnx I accepted answer just have one subquestion. ToUnixTimeSeconds() returns Int but .timeIntervalSince1970 return double. Are theese both number of seconds? Do you know? – 1110 Jan 06 '17 at 11:36
  • Yes. The Unix time is defined as number of seconds since 1970, 1st Jan in UTC. They use double for the same reason I am suggesting long - to avoid overflows in future. – Ashhar Hasan Jan 06 '17 at 11:38
  • Ah so the returned double must cast to long datatype and it is the same as .TotalSeconds then – 1110 Jan 06 '17 at 11:40
  • Yes. I would try to keep the double if you build for 32 bit systems since the long on 32 bit systems isn't long enough. If you exclusively build on 64-bit machines, it's good to convert to long to avoid rounding errors common with decimal datatypes. – Ashhar Hasan Jan 06 '17 at 11:42
0

This might work.

(DateTime.Now - new DateTime(1970,1,1)).TotalSeconds

This gets the date and subtracts the default epoch time of C# (01-01-01:00:00:00) making it start from 01-01-1970.

This is most probably the easiest way to get the same value.

Prajwal
  • 3,930
  • 5
  • 24
  • 50
  • Why are you getting miliseconds? Is swift timeIntervalSince1970 miliseconds or seconds? – 1110 Jan 06 '17 at 11:20