Here's what I tried so far:
var value = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds.ToString()
It gives me the answer below but I would like to get a whole number:
"1500092088.9501"
Here's what I tried so far:
var value = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds.ToString()
It gives me the answer below but I would like to get a whole number:
"1500092088.9501"
Below are a few examples of various ways you can deal with this sort of scenario
double secondsSince1970 = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
// int logic. ints are whole numbers so casting to an int will drop all decimals with no rounding.
Console.WriteLine(((long)secondsSince1970).ToString());
// Math logic. .Net gives us some handy Maths to work with rounding decimals
// Round up
Console.WriteLine(Math.Ceiling(secondsSince1970).ToString());
// Round down
Console.WriteLine(Math.Floor(secondsSince1970).ToString());
// Round nearest
Console.WriteLine(Math.Round(secondsSince1970).ToString());
EDIT: Changed the int logic to cast to a long
instead of an int
because the int.MaxValue
will be reached near the start of the year 2038
I would just use DateTimeOffset
to get the seconds count:
long secsSinceEpoch = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
This seems to be what you're looking for though, of course, you'd probably want to call ToString()
on that if you want it as an actual string:
var secsSinceEpoch = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
I thought it worth mentioning - If you want the number of seconds from the start of the epoch time, which is 1/1/1970, You don't need to do subtraction... You just need to get the current datetime and do the conversion to seconds.
Joe_DM provides a good answer to your rounding problem.
(Would leave as comment, but still a little short on rep :) )