New Date (). getTime () in .NET.

Basically, I want to do below in .NET, but I have no idea how to do this.

var d = new Date().getTime() + " milliseconds since 1970/01/01" 
+7
datetime
source share
7 answers

You would 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); 
+5
source share

I'm not sure you can get a UNIX date in .NET, but you have DateTime.Now as the equivalent new Date () (or new DateTime ())

As you got in the comment, you can get a TimeSpan object by sacrificing something in the lines ...

(First answer)

 DateTime.Now.Subtract(new DateTime(1970,1,1)).TotalMilliseconds 

Adding the final result for the sake of humanity ...

 var d = DateTime.Now.Subtract(new DateTime(1970,1,1).ToUniversalTime()).TotalMilliseconds + " milliseconds since 1970/01/01"; 

PS Where is John Skeet with his knowledge of the time when we need him: P

+9
source share

I wrote an extension method for myself some time ago.

Used like this:

  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; } } 
+2
source share

Subtraction is a way to do this, but all the answers I've seen so far are incorrectly configured for UTC.

You need 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); 
+2
source share

You can get there via DateTime and TimeSpan via DateTime.Subtract , something like:

 TimeSpan ts = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)); ts.TotalMilliseconds; // ...since The Epoch 
+1
source share

What about

 var s = string.format("{0} milliseconds since 1970/01/01", (DateTime.Now - DateTime.Parse("1970/01/01")).TotalMilliseconds); 
0
source share
 DateTime dt = new DateTime(); dt = DateTime.Now; TimeSpan dtNow = new TimeSpan(); dtNow = dt.Subtract(new DateTime(1970, 1, 1)); Console.WriteLine(dtNow.TotalMilliseconds); 

The bit is long compared to others, but it works.

-one
source share

All Articles