How to turn a UNIX timestamp into Datetime?

Asked

Viewed 58 times

1

I have a date field in the format UNIX timestamp, and I need to turn this field into a DateTime of C#. How to proceed?

Example of input: 1514959643539

Desired output: DateTime with correct date/time information (03/01/2018 06:07:23)

1 answer

1

The class System.DateTimeOffset has appropriate methods for handling UNIX timestamps in a C#development environment. We can do the desired transformation with the code below (the code was created to run on Linqpad, the function Dump() (that is specific to that application) simply print out what is in the variable in the most graphic way possible:

void Main()
{
    var dateTime = DateTimeOffset.FromUnixTimeMilliseconds(1514959643539).UtcDateTime;

    dateTime.Dump(); // 03/01/2018 06:07:23
}

Janela de execução do aplicativo LINQPad, exibindo na parte superior o código exibido logo acima, e na parte inferior o valor "03/01/2018 06:07:23" - que é o resultado da execução do código.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.