29

In C# how can I convert Unix-style timestamp to yyyy-MM-ddThh:mm:ssZ?

danny
  • 1,969
  • 3
  • 16
  • 26

9 Answers9

33

Start by converting your milliseconds to a TimeSpan:

var time = TimeSpan.FromMilliseconds(milliseconds);

Now, in .NET 4 you can call .ToString() with a format string argument. See http://msdn.microsoft.com/en-us/library/system.timespan.tostring.aspx

In previous versions of .NET, you'll have to manually construct the formatted string from the TimeSpan's properties.

Jay
  • 56,361
  • 10
  • 99
  • 123
24

new DateTime(numTicks * 10000)

The DateTime(long ticks) constructor is what you need. Each tick represents 100 nanoseconds so multiply by 10000 to get to 1 millisecond.

Babak Naffas
  • 12,395
  • 3
  • 34
  • 49
20

If the milliseconds is based on UNIX epoch time, then you can use:

var posixTime = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
var time = posixTime.AddMilliseconds(milliSecs);
Prakash G. R.
  • 4,746
  • 1
  • 24
  • 35
9

This worked for me:

DateTimeOffset.FromUnixTimeMilliseconds(milliseconds);

You can get just the DateTime from that if you need it.

mvandillen
  • 904
  • 10
  • 17
4

Here you go:

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);
        }
    }
superlogical
  • 14,332
  • 9
  • 66
  • 76
  • 1
    You need constants for all of those magic numbers. But if I had to guess (and I'll try them out), they represent that magic 1970 date.. in milliseconds from 1901. – Gerard ONeill Aug 26 '17 at 00:11
3

This sample will demonstrate the general idea, but you need to know if your starting date is DateTime.MinValue or something else:

int ms = 1000;                          // One second
var date = new DateTime(ms * 10000);    // The constructor takes number of 100-nanoseconds ticks since DateTime.MinValue (midnight, january 1st, year 1)
string formatted = date.ToString("yyyy-MM-ddTHH:mm:ssZ");
Console.WriteLine(formatted);
driis
  • 161,458
  • 45
  • 265
  • 341
1

You can construct your datetime from ticks:

long ticks = new DateTime(1979, 07, 28, 22, 35, 5, 
  new CultureInfo("en-US", false).Calendar).Ticks;
DateTime dt3 = new DateTime(ticks);
Console.Write(dt3.ToString("yyyy-MM-ddThh:mm:ssZ"));
VMAtm
  • 27,943
  • 17
  • 79
  • 125
0
    private static DateTime Milliseconds2Date(Double d)
    {         
        TimeSpan time = TimeSpan.FromMilliseconds(d);
        return new DateTime(1970, 1, 1) + time;
    }

    private static Double Date2Milliseconds(DateTime d)
    {

        var t = d.Subtract(new DateTime(1970, 1, 1));
        return t.TotalMilliseconds;            

    }
-5

This question should have the answer you need.

Short version:

DateTime date = new DateTime(long.Parse(ticks));
date.ToString("yyyy-MM-ddThh:mm:ssZ");
Community
  • 1
  • 1
Evan Powell
  • 960
  • 5
  • 4
  • 33
    I'm not sure why this was accepted, but ticks are NOT the same thing as milliseconds. You would need to multiply the millis by 10000 to get ticks for the DateTime constructor. – Yoten May 08 '12 at 19:31
  • 1
    Probably even better to multiply by TimeSpan.TicksPerMillisecond (which equals to 10000) – infografnet Jan 06 '15 at 15:22