Basically i want to do the below in .NET but i have no idea how to.
var d = new Date().getTime() + " milliseconds since 1970/01/01"
Basically i want to do the below in .NET but i have no idea how to.
var d = new Date().getTime() + " milliseconds since 1970/01/01"
I'm not really sure you can get a UNIX date in .NET, but you have DateTime.Now as an equvivalent of new Date() (or new DateTime())
As you got in the comment, it's possible to get a TimeSpan object by doning something in the lines of...
(First answer)
DateTime.Now.Subtract(new DateTime(1970,1,1)).TotalMilliseconds
Adding the final result for the sake of mankind...
var d = DateTime.Now.Subtract(new DateTime(1970,1,1).ToUniversalTime()).TotalMilliseconds + " milliseconds since 1970/01/01";
P.S. Where is Jon Skeet with his knowledge of time when we need him :P
You'd do something like this...
var ts = DateTime.UtcNow - new DateTime(1970,1,1);
var result = String.Format("{0} milliseconds since 1970/01/01", ts.TotalMilliseconds);
You can get there via the DateTime
and TimeSpan
structures via DateTime.Subtract
, something like:
TimeSpan ts = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1));
ts.TotalMilliseconds; // ...since The Epoch
DateTime dt = new DateTime();
dt = DateTime.Now;
TimeSpan dtNow = new TimeSpan();
dtNow = dt.Subtract(new DateTime(1970, 1, 1));
Console.WriteLine(dtNow.TotalMilliseconds);
Bit long-winded in comparison to others, but it works.
I wrote an extension method for myself a while back.
It's used like so:
double ticks = DateTime.UtcNow.UnixTicks();
Implementation:
public static class ExtensionMethods
{
// returns the number of milliseconds since Jan 1, 1970
// (useful for converting C# dates to JS dates)
public static double UnixTicks(this DateTime dt)
{
DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = dt.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return ts.TotalMilliseconds;
}
}
How about
var s = string.format("{0} milliseconds since 1970/01/01",
(DateTime.Now - DateTime.Parse("1970/01/01")).TotalMilliseconds);
Subtraction is the way to do it, but all the responses I've seen so far do not correctly adjust for UTC.
You want something like:
var ts = DateTime.UtcNow - new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc);
var result = String.Format("{0} milliseconds since 1970/01/01", ts.TotalMilliseconds);