简体   繁体   中英

How can I convert the number of seconds since Jan 1st 1970 into a datetime value?

I have a number that is the number of seconds since January 1st 1970. It was created with this:

 var utcNow = (int) Math.Truncate(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);

Now need to convert that number to a date in string form like this:

Tue, Jan 15, 2019

Can someone give me some suggestions on how I can do this. I think I can format it myself but I need a suggestion on how to convert the integer utcNow into a datetime first.

static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
...
DateTime time = epoch.AddSeconds(utcNow);

You can also use this in reverse:

var seconds = (time - epoch).TotalSeconds;

(which gives a double , but you can cast it to int or long etc)

Some answer are already given, and work. But this is, I believe, the most elegant way of doing it. I'm using DateTimeOffset.FromUnixTimeSeconds(int64)

DateTimeOffset dt = DateTimeOffset.FromUnixTimeSeconds(utcNow);

And now you can convert it into a DateTime Struct with help of this blog entry

Substract the given time from current time and it gives timespan instance, from that you can get total seconds

        var fromDate = new DateTime(1970,1 ,1);
        var diffrance = DateTime.UtcNow.Subtract(fromDate);
        Console.WriteLine(diffrance.TotalSeconds);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM