Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# version of Javascript Date.getTime()

Tags:

javascript

c#

What is the best way in c# to get the same result of javascript date.gettime() call?

The getTime() method returns the number of milliseconds since midnight of January 1, 1970 and the specified date.

like image 235
Michael Avatar asked Nov 15 '11 09:11

Michael


5 Answers

You can use this solution:

private int GetTime()
{
   var time = (DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1));
   return (int)(time.TotalMilliseconds + 0.5);
}

 
like image 185
Glory Raj Avatar answered Nov 12 '22 05:11

Glory Raj


Since JavaScript time is with respect to UTC, I think you will need something like this:

var st = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var t  = (DateTime.Now.ToUniversalTime() - st);
// t.TotalMilliseconds

Now you can use the TotalMilliseconds property of the Timespan.

like image 34
V4Vendetta Avatar answered Nov 12 '22 07:11

V4Vendetta


The correct implementation (assuming the current time) is as follows:

DateTime utcNow = DateTime.UtcNow;
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long ts = (long)((utcNow - epoch).TotalMilliseconds);
like image 7
Matt Johnson-Pint Avatar answered Nov 12 '22 05:11

Matt Johnson-Pint


The Java and JavaScript Date.getTime() methods return the number of milliseconds since 1 Jan 1970 00:00:00 GMT.

Since .NET represents dates in Ticks (1 Tick = 0.1 nanoseconds or 0.0001 milliseconds) since 1 Jan 0001 00:00:00 GMT, we must use a conversion formula where 621355968000000000 is the offset between the base dates in Ticks and 10000 the number of Ticks per Millisecond.

Ticks = (MilliSeconds * 10000) + 621355968000000000
MilliSeconds = (Ticks - 621355968000000000) / 10000
like image 6
Royi Namir Avatar answered Nov 12 '22 06:11

Royi Namir


I guess this will do the trick :)

public double MilliTimeStamp(DateTime TheDate)
        {
            DateTime d1 = new DateTime(1970, 1, 1);
            DateTime d2 = TheDate.ToUniversalTime();
            TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);

            return ts.TotalMilliseconds;
        }
like image 4
Issa Qandil Avatar answered Nov 12 '22 06:11

Issa Qandil