Cómo convertir milisegundos a formato de fecha en C#?


En C# ¿cómo puedo convertir la marca de tiempo de estilo Unix a yyyy-MM-DDThh:mm:ssZ?

Author: danny, 2011-09-07

8 answers

Comience por convertir sus milisegundos a TimeSpan:

var time = TimeSpan.FromMilliseconds(milliseconds);

Ahora, en.NET 4 puede llamar a .ToString() con un argumento de cadena de formato. Véase http://msdn.microsoft.com/en-us/library/system.timespan.tostring.aspx

En versiones anteriores de.NET, tendrá que construir manualmente la cadena formateada a partir de las propiedades del intervalo de tiempo.

 31
Author: Jay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-07 16:05:58

Nueva fecha y hora (Numsticks * 10000)

El constructor DateTime(long ticks) es lo que necesitas. Cada tick representa 100 nanosegundos así que multiplícalo por 10000 para llegar a 1 milisegundo.

 21
Author: Babak Naffas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-28 18:49:27

Si los milisegundos se basan en UNIX epoch time , entonces puede usar:

var posixTime = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
var time = posixTime.AddMilliseconds(milliSecs);
 18
Author: Prakash G. R.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-28 07:02:02

Esto funcionó para mí:

DateTimeOffset.FromUnixTimeMilliseconds(milliseconds);

Puede obtener solo la fecha y hora de eso si lo necesita.

 6
Author: mvandillen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-24 18:04:23

Este ejemplo demostrará la idea general, pero necesita saber si su fecha de inicio es DateTime.MinValue o algo más:

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);
 3
Author: driis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-07 16:08:42

Aquí tienes:

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);
        }
    }
 3
Author: superlogical,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-28 23:16:32

Puedes construir tu datetime a partir de 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"));
 1
Author: VMAtm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-07 16:03:24

Esta pregunta debe tener la respuesta que necesita.

Versión corta:

DateTime date = new DateTime(long.Parse(ticks));
date.ToString("yyyy-MM-ddThh:mm:ssZ");
 -5
Author: Evan Powell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:32