1

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.

Alan2
  • 23,493
  • 79
  • 256
  • 450
  • 1
    Possible duplicate of [How can I convert a Unix timestamp to DateTime and vice versa?](https://stackoverflow.com/questions/249760/how-can-i-convert-a-unix-timestamp-to-datetime-and-vice-versa) – MindSwipe Jan 15 '19 at 10:09

3 Answers3

3
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)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
3

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

MindSwipe
  • 7,193
  • 24
  • 47
2

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);
programtreasures
  • 4,250
  • 1
  • 10
  • 29