By Mark Ingram


2008-10-30 10:30:29 8 Comments

There is this example code, but then it starts talking about millisecond / nanosecond problems.

The same question is on MSDN, Seconds since the Unix epoch in C#.

This is what I've got so far:

public Double CreatedEpoch
{
  get
  {
    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
    TimeSpan span = (this.Created.ToLocalTime() - epoch);
    return span.TotalSeconds;
  }
  set
  {
    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
    this.Created = epoch.AddSeconds(value);
  }
}

18 comments

@AMieres 2019-09-17 12:38:50

System.DateTimeOffset.Now.ToUnixTimeSeconds()

@Riyaz Hameed 2019-09-04 14:37:31

Written a simplest extension that works for us. If anyone looks for it...

public static class DateTimeExtensions
{
    public static DateTime FromUnixTimeStampToDateTime(this string unixTimeStamp)
    {

        return DateTimeOffset.FromUnixTimeSeconds(long.Parse(unixTimeStamp)).UtcDateTime;
    }
}

@gl051 2012-04-13 19:55:35

From Wikipedia:

UTC does not change with a change of seasons, but local time or civil time may change if a time zone jurisdiction observes daylight saving time (summer time). For example, local time on the east coast of the United States is five hours behind UTC during winter, but four hours behind while daylight saving is observed there.

So this is my code:

TimeSpan span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0,DateTimeKind.Utc));
double unixTime = span.TotalSeconds;

@knocte 2013-05-06 06:25:36

but this returns a double, I guess one needs to cast to long?

@Fred 2015-07-23 13:09:16

Unix time conversion is new in .NET Framework 4.6.

You can now more easily convert date and time values to or from .NET Framework types and Unix time. This can be necessary, for example, when converting time values between a JavaScript client and .NET server. The following APIs have been added to the DateTimeOffset structure:

static DateTimeOffset FromUnixTimeSeconds(long seconds)
static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)
long DateTimeOffset.ToUnixTimeSeconds()
long DateTimeOffset.ToUnixTimeMilliseconds()

@Berend de Boer 2017-08-27 23:57:02

This does not give you local time, you get UTC.

@Deilan 2017-11-21 13:04:40

@BerenddeBoer That's a reasonable default. You may apply a custom offset after that as you want.

@Tanktalus 2018-09-11 17:18:39

@BerenddeBoer That misunderstands what unix time is. Unix time is seconds since midnight, Jan 1, 1970, UTC. Doesn't matter where you are, the number of seconds since that epoch doesn't change. Converting it to human readable local time displays are separate from this universal representation, as it should be.

@i3arnon 2013-12-27 06:55:45

I needed to convert a timeval struct (seconds, microseconds) containing UNIX time to DateTime without losing precision and haven't found an answer here so I thought I just might add mine:

DateTime _epochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private DateTime UnixTimeToDateTime(Timeval unixTime)
{
    return _epochTime.AddTicks(
        unixTime.Seconds * TimeSpan.TicksPerSecond +
        unixTime.Microseconds * TimeSpan.TicksPerMillisecond/1000);
}

@Yang Zhang 2019-02-16 11:42:50

From .net 4.6, you can do this:

var dateTime = DateTimeOffset.FromUnixTimeSeconds(unixDateTime).DateTime;

@mesut 2018-11-11 10:53:22

var dt = DateTime.Now; 
var unixTime = ((DateTimeOffset)dt).ToUnixTimeSeconds();

// 1510396991

var dt = DateTimeOffset.FromUnixTimeSeconds(1510396991);

// [11.11.2017 10:43:11 +00:00]

@i3arnon 2014-10-06 22:17:46

The latest version of .NET (v4.6) has added built-in support for Unix time conversions. That includes both to and from Unix time represented by either seconds or milliseconds.

  • Unix time in seconds to UTC DateTimeOffset:

DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);
  • DateTimeOffset to Unix time in seconds:

long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();
  • Unix time in milliseconds to UTC DateTimeOffset:

DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1000000);
  • DateTimeOffset to Unix time in milliseconds:

long unixTimeStampInMilliseconds = dateTimeOffset.ToUnixTimeMilliseconds();

Note: These methods convert to and from a UTC DateTimeOffset. To get a DateTime representation simply use the DateTimeOffset.UtcDateTime or DateTimeOffset.LocalDateTime properties:

DateTime dateTime = dateTimeOffset.UtcDateTime;

@yedevtxt 2017-07-12 16:35:20

@Berend de Boer 2017-08-27 23:56:14

This does not convert time to local time. You get UTC if you use DateTimeOffset.FromUnixTimeSeconds().

@i3arnon 2017-08-28 17:11:06

@BerenddeBoer You can use ToLocalTime if you want.

@Dan Diplo 2019-04-04 09:54:45

To get current time you can use long unixMilliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();

@madan 2018-06-18 07:36:54

public static class UnixTime
    {
        private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);

        public static DateTime UnixTimeToDateTime(double unixTimeStamp)
        {
            return Epoch.AddSeconds(unixTimeStamp).ToUniversalTime();
        }
    }

you can call UnixTime.UnixTimeToDateTime(double datetime))

@Felix Keil 2014-07-23 08:57:13

Be careful, if you need precision higher than milliseconds!

.NET (v4.6) methods (e.g. FromUnixTimeMilliseconds) don't provide this precision.

AddSeconds and AddMilliseconds also cut off the microseconds in the double.

These versions have high precision:

Unix -> DateTime

public static DateTime UnixTimestampToDateTime(double unixTime)
{
    DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
    long unixTimeStampInTicks = (long) (unixTime * TimeSpan.TicksPerSecond);
    return new DateTime(unixStart.Ticks + unixTimeStampInTicks, System.DateTimeKind.Utc);
}

DateTime -> Unix

public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
    DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
    long unixTimeStampInTicks = (dateTime.ToUniversalTime() - unixStart).Ticks;
    return (double) unixTimeStampInTicks / TimeSpan.TicksPerSecond;
}

@IamIC 2017-06-20 10:10:15

This is the correct answer. The others get the time zone incorrect on the convert back from timestamp.

@Max 2018-02-17 18:07:44

for DateTime->Java, just [code] return (long) unixTimeStampInTicks / TimeSpan.TicksPerMilliSecond; [/code]

@Ngoc Pham 2018-05-03 21:21:04

So in your UnixTimestampToDateTime, the supplied unixTime is still in seconds, right?

@Felix Keil 2018-05-04 04:56:51

@NgocPham yes it is

@ScottCher 2008-10-30 14:42:17

Here's what you need:

public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
{
    // Unix timestamp is seconds past epoch
    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
    return dtDateTime;
}

Or, for Java (which is different because the timestamp is in milliseconds, not seconds):

public static DateTime JavaTimeStampToDateTime( double javaTimeStamp )
{
    // Java timestamp is milliseconds past epoch
    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddMilliseconds( javaTimeStamp ).ToLocalTime();
    return dtDateTime;
}

@Luk 2008-11-03 17:32:40

AddSeconds doesn't seem to behave very well for values lesser than 0.1 milliseconds (iirc)

@Roman Starkov 2011-04-15 20:36:59

@Luk yes, a number of methods of DateTime/TimeSpan are inexplicably sub-millisecond impaired...

@Jim Schubert 2012-04-13 14:59:30

Time in Windows is handled by HAL and only close-to-accurate within 1ms to 15ms. More info is available in Windows Internals around page 112, if anyone is interested.

@ccook 2013-03-04 14:59:24

This answer risks truncating the seconds... A double is a floating number. The argument should be int/long/etc.

@Justin Johnson 2014-02-21 21:20:14

These methods should accept a long or int, not a double. Also, for the Java time stamps, there is no need to divide by 1000 and round. Just do dtDateTime.AddMilliseconds(javaTimeStamp).ToLocalTime();

@Mikael Vandmo 2014-10-03 10:26:14

Am I missing something here or can't you just do something like dateTime.ToFileTimeUtc() / 1000 + SOME_MAGIC_CONSTANT?

@Jonny 2014-12-08 08:31:00

Did you just miss the "vice versa"? How do we convert a DateTime to a timestamp?

@rookie1024 2016-05-18 02:49:15

For the .NET Framework 4.6 and above there is now static DateTimeOffset.FromUnixMilliseconds and DateTimeOffset.ToUnixMilliseconds.

@Nyerguds 2016-11-10 11:32:23

@JustinJohnson Actually, strangely, the AddSeconds and AddMilliseconds functions only accept doubles anyway.

@Anonymous Coward 2017-04-23 18:26:08

@ccook and JustinJohnson If the time to be converted is between 1970 and year 128000 there is no risk of millisecond truncation. Since Double is consistent with the DateTime implementation in C# I'd go with that.

@needfulthing 2018-08-22 14:34:21

System.DateTime dtDateTime = new DateTime.MinValue; should be sufficient.

@Soonts 2019-09-26 23:19:52

A better way to do the math without floating point errors is this: unixEpoch.AddTicks( TimeSpan.TicksPerSecond * seconds )

@orad 2015-04-28 01:22:11

See IdentityModel.EpochTimeExtensions

public static class EpochTimeExtensions
{
    /// <summary>
    /// Converts the given date value to epoch time.
    /// </summary>
    public static long ToEpochTime(this DateTime dateTime)
    {
        var date = dateTime.ToUniversalTime();
        var ticks = date.Ticks - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks;
        var ts = ticks / TimeSpan.TicksPerSecond;
        return ts;
    }

    /// <summary>
    /// Converts the given date value to epoch time.
    /// </summary>
    public static long ToEpochTime(this DateTimeOffset dateTime)
    {
        var date = dateTime.ToUniversalTime();
        var ticks = date.Ticks - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).Ticks;
        var ts = ticks / TimeSpan.TicksPerSecond;
        return ts;
    }

    /// <summary>
    /// Converts the given epoch time to a <see cref="DateTime"/> with <see cref="DateTimeKind.Utc"/> kind.
    /// </summary>
    public static DateTime ToDateTimeFromEpoch(this long intDate)
    {
        var timeInTicks = intDate * TimeSpan.TicksPerSecond;
        return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddTicks(timeInTicks);
    }

    /// <summary>
    /// Converts the given epoch time to a UTC <see cref="DateTimeOffset"/>.
    /// </summary>
    public static DateTimeOffset ToDateTimeOffsetFromEpoch(this long intDate)
    {
        var timeInTicks = intDate * TimeSpan.TicksPerSecond;
        return new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(timeInTicks);
    }
}

@JamesHoux 2018-12-14 02:47:54

This is good, but I'd suggest a small change: Use of type "long" should be changed to "Int32" or "int". "Long" implies there is significant precision, but there isn't. All of the math is only precise to 1 second so Int32 would be more suggestive of what you'd expect from a Unix timestamp

@orad 2018-12-14 20:42:36

I think it's due to DateTime.Ticks being Int64 (long), so they're avoiding an extra unchecked cast.

@Dmitry Fedorkov 2011-09-29 11:12:52

DateTime to UNIX timestamp:

public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
    return (TimeZoneInfo.ConvertTimeToUtc(dateTime) - 
           new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}

@superlogical 2015-05-28 23:35:28

For .NET 4.6 and later:

public static class UnixDateTime
{
    public static DateTimeOffset FromUnixTimeSeconds(long seconds)
    {
        if (seconds < -62135596800L || seconds > 253402300799L)
            throw new ArgumentOutOfRangeException("seconds", seconds, "");

        return new DateTimeOffset(seconds * 10000000L + 621355968000000000L, TimeSpan.Zero);
    }

    public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)
    {
        if (milliseconds < -62135596800000L || milliseconds > 253402300799999L)
            throw new ArgumentOutOfRangeException("milliseconds", milliseconds, "");

        return new DateTimeOffset(milliseconds * 10000L + 621355968000000000L, TimeSpan.Zero);
    }

    public static long ToUnixTimeSeconds(this DateTimeOffset utcDateTime)
    {
        return utcDateTime.Ticks / 10000000L - 62135596800L;
    }

    public static long ToUnixTimeMilliseconds(this DateTimeOffset utcDateTime)
    {
        return utcDateTime.Ticks / 10000L - 62135596800000L;
    }

    [Test]
    public void UnixSeconds()
    {
        DateTime utcNow = DateTime.UtcNow;
        DateTimeOffset utcNowOffset = new DateTimeOffset(utcNow);

        long unixTimestampInSeconds = utcNowOffset.ToUnixTimeSeconds();

        DateTimeOffset utcNowOffsetTest = UnixDateTime.FromUnixTimeSeconds(unixTimestampInSeconds);

        Assert.AreEqual(utcNowOffset.Year, utcNowOffsetTest.Year);
        Assert.AreEqual(utcNowOffset.Month, utcNowOffsetTest.Month);
        Assert.AreEqual(utcNowOffset.Date, utcNowOffsetTest.Date);
        Assert.AreEqual(utcNowOffset.Hour, utcNowOffsetTest.Hour);
        Assert.AreEqual(utcNowOffset.Minute, utcNowOffsetTest.Minute);
        Assert.AreEqual(utcNowOffset.Second, utcNowOffsetTest.Second);
    }

    [Test]
    public void UnixMilliseconds()
    {
        DateTime utcNow = DateTime.UtcNow;
        DateTimeOffset utcNowOffset = new DateTimeOffset(utcNow);

        long unixTimestampInMilliseconds = utcNowOffset.ToUnixTimeMilliseconds();

        DateTimeOffset utcNowOffsetTest = UnixDateTime.FromUnixTimeMilliseconds(unixTimestampInMilliseconds);

        Assert.AreEqual(utcNowOffset.Year, utcNowOffsetTest.Year);
        Assert.AreEqual(utcNowOffset.Month, utcNowOffsetTest.Month);
        Assert.AreEqual(utcNowOffset.Date, utcNowOffsetTest.Date);
        Assert.AreEqual(utcNowOffset.Hour, utcNowOffsetTest.Hour);
        Assert.AreEqual(utcNowOffset.Minute, utcNowOffsetTest.Minute);
        Assert.AreEqual(utcNowOffset.Second, utcNowOffsetTest.Second);
        Assert.AreEqual(utcNowOffset.Millisecond, utcNowOffsetTest.Millisecond);
    }
}

@Jeppe Stig Nielsen 2016-02-19 10:32:21

I do not understand. In .NET 4.6, the BCL already has those methods (see e.g. my comment to the question above, or some of the other new answers (2015). So what should the point be in writing them again? Did you mean that your answer was a solution for versions prior to 4.6?

@Luk 2008-10-30 10:53:34

A Unix tick is 1 second (if I remember well), and a .NET tick is 100 nanoseconds.

If you've been encountering problems with nanoseconds, you might want to try using AddTick(10000000 * value).

@ScottCher 2008-10-30 14:44:16

Unix is seconds past epoch - which is 1/1/70.

@Hot Licks 2014-08-12 17:26:21

DateTime unixEpoch = DateTime.ParseExact("1970-01-01", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
DateTime convertedTime = unixEpoch.AddMilliseconds(unixTimeInMillisconds);

Of course, one can make unixEpoch a global static, so it only needs to appear once in your project, and one can use AddSeconds if the UNIX time is in seconds.

To go the other way:

double unixTimeInMilliseconds = timeToConvert.Subtract(unixEpoch).TotalMilliseconds;

Truncate to Int64 and/or use TotalSeconds as needed.

@n8CodeGuru 2011-04-12 20:34:51

I found the right answer just by comparing the conversion to 1/1/1970 w/o the local time adjustment;

DateTime date = new DateTime(2011, 4, 1, 12, 0, 0, 0);
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
TimeSpan span = (date - epoch);
double unixTime =span.TotalSeconds;

@Chris Thoman 2012-10-07 16:14:31

To supplement ScottCher's answer, I recently found myself in the annoying scenario of having both seconds and milliseconds UNIX timestamps arbitrarily mixed together in an input data set. The following code seems to handle this well:

static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
static readonly double MaxUnixSeconds = (DateTime.MaxValue - UnixEpoch).TotalSeconds;

public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
{
   return unixTimeStamp > MaxUnixSeconds
      ? UnixEpoch.AddMilliseconds(unixTimeStamp)
      : UnixEpoch.AddSeconds(unixTimeStamp);
}

@Sam Grondahl 2013-09-16 22:40:05

Be careful when not using the DateTimeKind argument, since the constructed DateTime will be in the computer's local time (thanks for the code, Chris)!

@Øyvind 2018-05-17 07:24:52

Beware - this will not work for unix timestamps for dates prior to the 11th of January 1978 if they're represented in milliseconds. A unix datestamp of 253324800 (seconds) gives the correct date of 11.01.1978, whereas the millisecond representation 253324800000 gives a date of 18.07.9997. This may have worked for your data set, but it's not a general solution.

Related Questions

Sponsored Content

20 Answered Questions

[SOLVED] Converting string into datetime

  • 2009-01-21 18:00:29
  • Oli
  • 2875426 View
  • 2125 Score
  • 20 Answer
  • Tags:   python datetime

43 Answered Questions

[SOLVED] How do you convert a byte array to a hexadecimal string, and vice versa?

  • 2008-11-22 10:03:13
  • alextansc
  • 838132 View
  • 1352 Score
  • 43 Answer
  • Tags:   c# arrays hex

13 Answered Questions

[SOLVED] How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

  • 2011-08-09 16:43:08
  • SuperString
  • 366344 View
  • 338 Score
  • 13 Answer
  • Tags:   python datetime epoch

39 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

16 Answered Questions

[SOLVED] Converting a String to DateTime

  • 2009-05-28 05:01:02
  • dban
  • 1309499 View
  • 575 Score
  • 16 Answer
  • Tags:   c# datetime

43 Answered Questions

[SOLVED] How to return only the Date from a SQL Server DateTime datatype

15 Answered Questions

[SOLVED] Converting unix timestamp string to readable date

39 Answered Questions

[SOLVED] Should I use the datetime or timestamp data type in MySQL?

54 Answered Questions

[SOLVED] How can I pretty-print JSON in a shell script?

Sponsored Content