14

Possible Duplicate:
How to convert UNIX timestamp to DateTime and vice versa?

How can I create a unix timestamp in C#? (e.g. 2012-10-10 14:00:00 -> 1349877600)

Community
  • 1
  • 1
LostPhysx
  • 3,573
  • 8
  • 43
  • 73

2 Answers2

38
private double ConvertToTimestamp(DateTime value)
{
    //create Timespan by subtracting the value provided from
    //the Unix Epoch
    TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());

    //return the total seconds (which is a UNIX timestamp)
    return (double)span.TotalSeconds;
}
John Woo
  • 258,903
  • 69
  • 498
  • 492
  • 12
    Why "double"? Wouldn't a long integer be a better model for seconds? (And more consistent with the Unix representation?) – William T. Mallard Jan 31 '14 at 19:50
  • @WilliamT.Mallard If you want a `long`, I suggest `return span.Ticks / TimeSpan.TicksPerSecond;`. However, since 2015, the BCL has a built in method, `((DateTimeOffset)value).ToUnixTimeSeconds()`. – Jeppe Stig Nielsen Jul 20 '16 at 13:19
-1

DateTime.UtcNow - new DateTime(2012,10,10,14,0,0)).TotalSeconds

aserwin
  • 1,040
  • 2
  • 16
  • 34
  • 2
    A) You're missing a paren, I'm assuming it should go before `DateTime.UtcNow`, yes? And shouldn't `new DateTime(2012,10,10,14,0,0)` be the Unix epoch 1/1/1970? – William T. Mallard Jan 31 '14 at 19:57