154

Possible Duplicate:
How do you convert epoch time in C#?

I'm trying to figure out how to get the epoch time in C#. Similar to the timestamps given on this website: http://www.epochconverter.com/

Does DateTime have a method for that?

Community
  • 1
  • 1
James Jeffery
  • 2,011
  • 4
  • 19
  • 15

1 Answers1

237
TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1);
int secondsSinceEpoch = (int)t.TotalSeconds;
Console.WriteLine(secondsSinceEpoch);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 11
    Sure, if you believe the epoch is 1970-01-01T00:00:00, like any Unix system. But the .NET epoch is 0001-01-01T00:00:00, which is better known as `DateTime.MinValue`. – Ross Patterson Feb 26 '12 at 16:27
  • 50
    Sure, but a lot of applications still use the 1970 epoch, like OAuth, for example. – froggythefrog Mar 17 '13 at 05:08
  • @froggythefrog and SWT tokens http://msdn.microsoft.com/en-us/library/windowsazure/hh781551.aspx – user1477388 Sep 27 '13 at 13:13
  • 3
    isn't it supposed to be milliseconds? It's missing a few zeroes on the end – Sinaesthetic Jul 12 '15 at 01:08
  • 3
    @Sinaesthetic Epoch Time is defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970 - https://en.wikipedia.org/wiki/Unix_time – dynamiclynk Mar 30 '16 at 21:39
  • 1
    @Sinaesthetic You must be used to the Java implementation, where `System.currentTimeMillis()` is the number of millis since epoch. If you're determined to use millis instead, use `long millisecondsSinceEpoch = (long) t.TotalMilliseconds;` instead. – arkon Aug 01 '16 at 00:50
  • 185
    from .Net 4.6 and above use DateTimeOffset.Now.ToUnixTimeSeconds() – Saikat Chakraborty Oct 14 '16 at 10:07
  • 8
    in first string the Epoch time is created by constructor, which returns DateTime object with unspecified kind, so use `new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)` instead to avoid substraction of unspecified datetime from Utc. – Oleg Savelyev Aug 31 '17 at 12:30
  • @OlegSavelyev I tested your theory, and it doesn't make a difference. My C# app is hosted with local time offset 6 hours from UTC and I get the same value either way. – Timothy Kanski Nov 07 '17 at 04:29
  • 3
    @SaikatChakraborty Could you post your comment as an answer please? – Simon Achmüller May 16 '19 at 11:51
  • @Sinaesthetic t.TotalSeconds will return in seconds only. If you want in milliseconds, you can go for t.TotalMilliseconds. – Yash Mochi Aug 23 '20 at 14:38
  • 2
    Since .NET Core 2.1 `DateTime.UnixEpoch` is equivalent to `00:00:00.0000000 UTC, January 1, 1970` https://learn.microsoft.com/en-us/dotnet/api/system.datetime.unixepoch?view=netcore-2.1 – Pierre Nov 03 '20 at 09:10
  • 2
    For milliseconds in .NET 4.6 onwards: `DateTimeOffset.Now.ToUnixTimeMilliseconds()` – jcady Nov 13 '20 at 22:22