如何将JavaScript日期对象转换为刻度

问题描述 投票:64回答:6

我应该如何将JavaScript日期对象转换为刻度?我希望在同步数据后使用刻度来获取C#应用程序的确切日期。

c# javascript
6个回答
99
投票

如果要将DateTime对象转换为通用刻度,请使用以下代码段:

var ticks = ((yourDateObject.getTime() * 10000) + 621355968000000000);

一毫秒内有10000个刻度。并且在0001年1月1日到1970年1月1日之间有621.355.968.000.000.000个小时。


48
投票

JavaScript Date类型的起源是Unix时代:1970年1月1日午夜。

.NET DateTime类型的来源是0001年1月1日午夜。

您可以将JavaScript Date对象转换为.NET标记,如下所示:

var yourDate = new Date();  // for example

// the number of .net ticks at the unix epoch
var epochTicks = 621355968000000000;

// there are 10000 .net ticks per millisecond
var ticksPerMillisecond = 10000;

// calculate the total number of .net ticks for your date
var yourTicks = epochTicks + (yourDate.getTime() * ticksPerMillisecond);

29
投票

如果用“ticks”表示“自纪元以来毫秒”这样的东西,你可以调用“.getTime()”。

var ticks = someDate.getTime();

MDN documentation,返回的值是

整数值,表示自1970年1月1日00:00:00 UTC(Unix Epoch)以来的毫秒数。


6
投票

扩展接受的答案为什么添加635646076777520000

Javascript new Date().getTime() or Date.now()将返回从midnight of January 1, 1970传递的毫秒数。

在.NET(sourceRemarks部分)

DateTime值类型表示日期和时间,其值为00:00:00(午夜),1月1日,0001 Anno Domini(Common Era)到11:59:59 PM,12999年12月31日,公元9999年(CE)在Gregorian日历。

621355968000000000是从midnight Jan 1 01 CEmidnight Jan 1 1970的蜱的价值

所以,在.NET中

  Console.Write(new DateTime(621355968000000000))
  // output 1/1/1970 12:00:00 AM

因此将javascript时间转换为.Net ticks

 var currentTime = new Date().getTime();

 // 10,000 ticks in 1 millisecond
 // jsTicks is number of ticks from midnight Jan 1, 1970
 var jsTicks = currentTime * 10000;

 // add 621355968000000000 to jsTicks
 // netTicks is number of ticks from midnight Jan 1, 01 CE
 var netTicks = jsTicks + 621355968000000000;

现在,在.NET中

 Console.Write(new DateTime(netTicks))
 // output current time

5
投票

JavaScript中的日期也包含偏移量。如果你需要摆脱它使用以下:

return ((date.getTime() * 10000) + 621355968000000000) - (date.getTimezoneOffset() * 600000000);

我使用Skeikh的解决方案并减去'offset'的刻度。


2
投票

那应该是date.GetTime()。请注意C#和Javascript使用不同的初始日期,所以使用这样的东西转换为C#DateTime。

public static DateTime GetDateTime(long jsSeconds)
{
    DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    return unixEpoch.AddSeconds(jsSeconds);
}
© www.soinside.com 2019 - 2024. All rights reserved.