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#?
-
2Possible duplicate of [How can I convert a Unix timestamp to DateTime and vice versa?](https://stackoverflow.com/questions/249760/how-can-i-convert-a-unix-timestamp-to-datetime-and-vice-versa) – Nicol Bolas May 31 '19 at 17:44
16 Answers
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 of DateTime
, though beware
the timezone. To get the current timestamp:
DateTimeOffset.UtcNow.ToUnixTimeSeconds()
To get the timestamp from a DateTime
:
DateTime currentTime = DateTime.UtcNow;
long unixTime = ((DateTimeOffset)currentTime).ToUnixTimeSeconds();

- 15,441
- 3
- 26
- 42
-
6Until the [`Unix Millenium Bug`](https://en.wikipedia.org/wiki/Year_2038_problem) hits :) – Matt Borja Jun 23 '16 at 22:53
-
95@MattBorja Thankfully, it returns an `Int64` - by the time that rolls over, we'd not be using Earth years anymore for lack of an Earth. – Bob Jun 24 '16 at 00:59
-
4@Ony, `DateTime.Now.ToFileTimeUtc()` does **not** return the same as `DateTimeOffset.Now.ToUnixTimeSeconds()`. According to [MSDN](https://msdn.microsoft.com/en-us/library/system.datetime.tofiletimeutc(v=vs.110).aspx), “A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC).” – Alexandre Aug 02 '17 at 22:17
-
17You can get the UTC unixtimestamp with: DateTimeOffset.UtcNow.ToUnixTimeSeconds() – Yair Levi Jan 09 '18 at 22:13
-
2@Lost_In_Library: it is AN answer, but not THE answer, as not everybody uses 4.6 (or is able to use, for whatever reason) – bizzehdee Apr 27 '18 at 10:13
-
Oneline for those who want to modify the current date: `DateTimeOffset.Now.AddDays(365).ToUnixTimeSeconds()` – wp78de Dec 13 '18 at 20:26
-
I want my date-time to be 10days ago, and using the above came up with this: long initialUNIXTime = DateTimeOffset.Now.AddDays(-10).ToUnixTimeSeconds(); // i.e. DateTimeOffset has a Now() method of its own, so no need to involve DateTime class. – Zeek2 May 19 '21 at 10:33
-
-
Note: Now vs UtcNow does not matter here - "This method first converts the current instance to UTC before returning its Unix time". https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tounixtimeseconds – ryanwebjackson Feb 12 '23 at 19:01
You get a unix timestamp in C# by using DateTime.UtcNow
and subtracting the epoch time of 1970-01-01.
e.g.
Int32 unixTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
DateTime.UtcNow
can be replaced with any DateTime
object that you would like to get the unix timestamp for.
There is also a field, DateTime.UnixEpoch
, which is very poorly documented by MSFT, but may be a substitute for new DateTime(1970, 1, 1)

- 20,289
- 11
- 46
- 76
-
35Commenting on behalf of @wdhough. "This answer has limitation with the limit of Int32 which is, I believe, 2,147,483,647. According to http://www.onlineconversion.com/unix_time.htm this equates to a time of Tue, 19 Jan 2038 03:14:07 GMT I guess any alternative number type, double, long, etc will ultimately have a limit too, but I thought it worth mentioning. I choose long here as I wanted a whole number. Hope this helps" – IsmailS May 21 '14 at 12:24
-
15The unix timestamp is traditionally a 32 bit integer, and has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. – the_nuts Aug 04 '14 at 13:43
-
9Or using integer arythmetic: `DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).Ticks / TimeSpan.TicksPerSecond;` – Anton Petrov Jul 27 '16 at 16:01
-
2
-
@jjxtra DateTime does not care about the zone flag, and only takes into account the numbers when doing mathematical operations. DateTimeOffset is a smarter, and does take into account of the timezone flag. This is purposely done by .NET team. – Ghasan غسان Jan 24 '18 at 07:57
-
1The comment from @jjxtra seems correct to me and the given answer does not work in my case because DateTime(1970, 1, 1) is considered local time by the .NET Framework (I'm in UTC+1 zone). So the timestamp I get is actually the current UTC Date minus the 1st january 1970 in UTC+1 : I get a one hour leap. From what I understand, both date should be expressed with the same UTC offset so that this code works correctly. – Marshall777 Feb 14 '19 at 15:23
-
2The unix timestamp will suffer from a Y2K style problem in 2038: https://en.wikipedia.org/wiki/Year_2038_problem – Matthew Oct 18 '19 at 02:10
-
3This answer is not the best (see the one from @rstackhouse below) and it is dangerous. Like it was already posted, this implementation will suffer from an integer overflow in the year 2038. I would not recommend to use it! – lutzhell Oct 18 '19 at 06:28
-
1You are saving a timestamp in a type of Int32, this will potentially overflow – Damien Doumer Jun 18 '20 at 07:03
-
2As for .NetCore 2.1 there is a new constant 'DateTime.UnixEpoch', so you can simply use the following code: var timestamp = DateTime.UtcNow.Subtract(DateTime.UnixEpoch).TotalSeconds; – LaoR Aug 21 '20 at 14:53
-
1the Armageddon is going to happen on 2038-01-19 at 03:14:08 precisely ;) – Boppity Bop Nov 09 '20 at 12:39
-
2BTW: `DateTime.UnixEpoch` is defined to be in UTC. So ensure your variable is also in UTC (if you aren't simply using `DateTime.UtcNow`). E.g., `someNotUtcDateTimeVariable.ToUniversalTime().Subtract(DateTime.UnixEpoch).TotalSeconds()`. – Jesse Chisholm Feb 12 '22 at 20:29
-
Check my answer from 2021 to avoid 2038 and use UTC: https://stackoverflow.com/a/70372296/888472 – Leandro Bardelli Apr 12 '23 at 13:07
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.
long epochTicks = new DateTime(1970, 1, 1).Ticks;
long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond);
or
TimeSpan epochTicks = new TimeSpan(new DateTime(1970, 1, 1).Ticks);
TimeSpan unixTicks = new TimeSpan(DateTime.UtcNow.Ticks) - epochTicks;
double unixTime = unixTicks.TotalSeconds;

- 2,286
- 16
- 23

- 537
- 4
- 3
-
1Error for the second solution: Cannot convert source type 'double' to target type 'long'. – Egor Okhterov Sep 04 '15 at 15:45
-
-
10`new DateTime(1970, 1, 1)` creates a time with unspecified `Kind` property. What you really want to `new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)` to be truly correct – detunized Apr 13 '17 at 14:39
-
2From .NET Core 2.1 You can use DateTime.UnixEpoch instead of new DateTime(1970, 1, 1) see https://learn.microsoft.com/en-us/dotnet/api/system.datetime.unixepoch?view=netcore-3.1 – SomeDeveloper May 14 '20 at 12:56
This is what I use:
public long UnixTimeNow()
{
var timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
return (long)timeSpan.TotalSeconds;
}
Keep in mind that this method will return the time as Coordinated Univeral Time (UTC).

- 2,762
- 1
- 30
- 36
-
(TotalSeconds has `double` type; casting it to long will cause loss of precision.) – frankish Oct 02 '19 at 11:54
-
1You right, but we don't have to worry about that for several thousand years :) – Bartłomiej Mucha Oct 07 '19 at 16:33
Truncating .TotalSeconds
is important since it's defined as the 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.
/// <summary>
/// Converts a given DateTime into a Unix timestamp
/// </summary>
/// <param name="value">Any DateTime</param>
/// <returns>The given DateTime in Unix timestamp format</returns>
public static int ToUnixTimestamp(this DateTime value)
{
return (int)Math.Truncate((value.ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
}
/// <summary>
/// Gets a Unix timestamp representing the current moment
/// </summary>
/// <param name="ignored">Parameter ignored</param>
/// <returns>Now expressed as a Unix timestamp</returns>
public static int UnixTimestamp(this DateTime ignored)
{
return (int)Math.Truncate((DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
}

- 15,361
- 6
- 36
- 57
-
3Extension method is clearly the way to do this neatly. This is an excellent, mature answer - and i don't understand why it has so few votes. Pretty sure that Robba is correct - casting the output as (int) automatically truncates the result. (Literally ignoring the decimal part of the double). – Stephanie Apr 23 '15 at 07:52
-
7
-
I like the first extension. The second is just a utility method, doesn't deserve to be an extension. – Jesse Chisholm Feb 12 '22 at 20:35
-
Note that `int32` will fail to cover timestamps beyond `19 Jan 2038 03:14:07 GMT` due to it's integer size limitation. – dognose Jun 16 '23 at 09:53
With .NET 6.0, and using long
to avoid the 2038
problem:
From DateTime.UtcNow to UnixTime
long seconds = (long)DateTime.UtcNow.Subtract(DateTime.UnixEpoch).TotalSeconds;
seconds
will contains the seconds since 01/01/1970 (UnixTime)
From UnixTime to DateTime.UtcNow
DateTime timestamp = DateTime.UnixEpoch.AddSeconds(seconds);
Fiddle: https://dotnetfiddle.net/xNhO6q

- 18,680
- 13
- 103
- 118

- 10,561
- 15
- 79
- 116
-
Why do this over the `ToUnixTimeSeconds`/`FromUnixTimeSeconds` methods that already exist? – Bob Aug 09 '23 at 02:24
Updated code from Brad with few things: You don't need Math.truncate, conversion to int or long automatically truncates the value. In my version I am using long instead of int (We will run out of 32 bit signed integers in 2038 year). Also, added timestamp parsing.
public static class DateTimeHelper
{
/// <summary>
/// Converts a given DateTime into a Unix timestamp
/// </summary>
/// <param name="value">Any DateTime</param>
/// <returns>The given DateTime in Unix timestamp format</returns>
public static long ToUnixTimestamp(this DateTime value)
{
return (long)(value.ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
}
/// <summary>
/// Gets a Unix timestamp representing the current moment
/// </summary>
/// <param name="ignored">Parameter ignored</param>
/// <returns>Now expressed as a Unix timestamp</returns>
public static long UnixTimestamp(this DateTime ignored)
{
return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
}
/// <summary>
/// Returns a local DateTime based on provided unix timestamp
/// </summary>
/// <param name="timestamp">Unix/posix timestamp</param>
/// <returns>Local datetime</returns>
public static DateTime ParseUnixTimestamp(long timestamp)
{
return (new DateTime(1970, 1, 1)).AddSeconds(timestamp).ToLocalTime();
}
}

- 150
- 1
- 7
-
It should be `AddMilliseconds` for the `ParseUnixTimestamp(..)` method. Not `AddSeconds` – Mahmut EFE Mar 31 '22 at 00:49
-
I saw timestamps in seconds and in other places in milliseconds, though usually when we talk about Unix timestamp, we talk about seconds. This version is in seconds as in most places. – Sylwester Kogowski May 19 '23 at 04:48
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.
DateTime now = UtcNow();
// milliseconds Not included.
DateTime nowToTheSecond = new DateTime(now.Year,now.Month,now.Day,now.Hour,now.Minute,now.Second);
TimeSpan span = (date - new DateTime(1970, 1, 1, 0, 0, 0, 0));
Assert.That(span.Milliseconds, Is.EqualTo(0)); // passes.

- 121
- 1
- 8
Below is a 2-way extension class that supports:
- Timezone localization
- Input\output in seconds or milliseconds.
In OP's case, usage is:
DateTime.Now.ToUnixtime();
or
DateTime.UtcNow.ToUnixtime();
Even though a direct answer exists, I believe using a generic approach is better. Especially because it's most likely a project that needs a conversion like this, will also need these extensions anyway, so it's better to use the same tool for all.
public static class UnixtimeExtensions
{
public static readonly DateTime UNIXTIME_ZERO_POINT = new DateTime(1970, 1, 1, 0, 0,0, DateTimeKind.Utc);
/// <summary>
/// Converts a Unix timestamp (UTC timezone by definition) into a DateTime object
/// </summary>
/// <param name="value">An input of Unix timestamp in seconds or milliseconds format</param>
/// <param name="localize">should output be localized or remain in UTC timezone?</param>
/// <param name="isInMilliseconds">Is input in milliseconds or seconds?</param>
/// <returns></returns>
public static DateTime FromUnixtime(this long value, bool localize = false, bool isInMilliseconds = true)
{
DateTime result;
if (isInMilliseconds)
{
result = UNIXTIME_ZERO_POINT.AddMilliseconds(value);
}
else
{
result = UNIXTIME_ZERO_POINT.AddSeconds(value);
}
if (localize)
return result.ToLocalTime();
else
return result;
}
/// <summary>
/// Converts a DateTime object into a Unix time stamp
/// </summary>
/// <param name="value">any DateTime object as input</param>
/// <param name="isInMilliseconds">Should output be in milliseconds or seconds?</param>
/// <returns></returns>
public static long ToUnixtime(this DateTime value, bool isInMilliseconds = true)
{
if (isInMilliseconds)
{
return (long)value.ToUniversalTime().Subtract(UNIXTIME_ZERO_POINT).TotalMilliseconds;
}
else
{
return (long)value.ToUniversalTime().Subtract(UNIXTIME_ZERO_POINT).TotalSeconds;
}
}
}

- 59
- 1
- 3
-
Be careful not to confuse the milliseconds and seconds formats (best case is an exception, worst is illogical conversion) I've defaulted the input\output to the milliseconds format. If you prefer to use the seconds format as default, just switch the isInMilliseconds=true (in both methods) to false. – SingleFlake Apr 08 '20 at 15:55
This is what I use.
public class TimeStamp
{
public Int32 UnixTimeStampUTC()
{
Int32 unixTimeStamp;
DateTime currentTime = DateTime.Now;
DateTime zuluTime = currentTime.ToUniversalTime();
DateTime unixEpoch = new DateTime(1970, 1, 1);
unixTimeStamp = (Int32)(zuluTime.Subtract(unixEpoch)).TotalSeconds;
return unixTimeStamp;
}
}

- 49
- 1
- 1
I've spliced together the most elegant approaches to this utility method:
public static class Ux {
public static decimal ToUnixTimestampSecs(this DateTime date) => ToUnixTimestampTicks(date) / (decimal) TimeSpan.TicksPerSecond;
public static long ToUnixTimestampTicks(this DateTime date) => date.ToUniversalTime().Ticks - UnixEpochTicks;
private static readonly long UnixEpochTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
}

- 3,786
- 2
- 36
- 56
There is a ToUnixTimeMilliseconds for DateTimeOffset in System
You can write similar method for DateTime:
public static long ToUnixTimeSeconds(this DateTime value)
{
return value.Ticks / 10000000L - 62135596800L;
}
10000000L - converting ticks to seconds
62135596800L - converting 01.01.01 to 01.01.1978
There is no problem with Utc and leaks

- 2,747
- 5
- 27
- 39
-
see https://stackoverflow.com/questions/58391011/explain-tounixtimemilliseconds#58391256 – Timur Lemeshko Oct 15 '19 at 10:01
I think this would work better to get the unix timestamp from any DateTime object. I am using .net Core 3.1.
DateTime foo = DateTime.Now;
long unixTime = ((DateTimeOffset)foo ).ToUnixTimeMilliseconds();

- 21
- 4
I used this after struggling for a while, it caters to the timezone offset as well:
public double Convert_DatTime_To_UNIXDATETIME(DateTime dt)
{
System.DateTime from_date = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
double unix_time_since = dt.Subtract(from_date).TotalMilliseconds;
TimeSpan ts_offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);
double offset = ts_offset.TotalMilliseconds;
return unix_time_since - offset;
}

- 9
- 2
If you have a UTC TimeStamp
as a long
in Tick
form there is an even faster shortcut for this.
/// <summary>
/// Convert Ticks to Unix Timestamp
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static long ToUnixTimestamp(long time)
{
return (time - 621355968000000000) / TimeSpan.TicksPerMillisecond;
}
The simple code that I am using:
public static long CurrentTimestamp()
{
return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds * 1000);
}
This code is giving unix timestamp, total milliseconds from 1970-01-01 to now.

- 51
- 2
- 4