How to get the unix timestamp in C#
Solution 1:
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.Now.ToUnixTimeSeconds()
To get the timestamp from a DateTime
:
DateTime foo = DateTime.Now;
long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds();
Solution 2:
You get a unix timestamp in C# by using DateTime.UtcNow
and subtracting the epoch time of 1970-01-01.
e.g.
Int32 unixTimestamp = (Int32)(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)
Solution 3:
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;
Solution 4:
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).
Solution 5:
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);
}