andrey.shedko andrey.shedko - 1 year ago 87
C# Question

Conversion to Unix timestamp is not working

I'm trying to convert

to Unix timestamp.

static long ToUnixTime(DateTime dateTime)
var dateTimeOffset = new DateTimeOffset(dateTime);
return dateTimeOffset.ToUnixTimeSeconds();

But this function always return timestamp equal to something "Sun Jan 18 1970" instead of current DateTime. What is wrong with this?

Amy Amy
Answer Source

The current date as expressed as a Unix timestamp is 1501093539, more or less.

I think you're checking yourself wrong; if I edit my code to add milliseconds, I get 1/18/1970. But unix times aren't in milliseconds. They're in seconds.

var dt = DateTime.Now;
var offset = new DateTimeOffset(dt);
var unix = offset.ToUnixTimeSeconds();

dt = new DateTime(1970,1,1,0,0,0);
dt = dt.AddSeconds(unix);
Debug.WriteLine(dt);        // gives current date back

Change it to AddSeconds and you'll get the current date. Change it to AddMilliseconds and you'll get January 18th, 1970. Your code is actually fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download