JavaScript中的VB Now.Ticks等效物

4
我该如何在JavaScript中复制这个?
Now.Ticks.ToString
5个回答

8

这个问题没有确切的答案。你提出了两个问题:

  1. How do I get the current date & time in javascript? This is easy, just write

    var now = new Date();
    
  2. How do I get the number of ticks since Januari 1, 0001? This one is harder, because javascript doesn't work with ticks, but with milliseconds, and the offset is Januari 1, 1970 instead.

    You can start with now.getTime() to get the milliseconds since Jan 1, 1970, and then multiply this with 10000. I just calculated the number of ticks between 0001-01-01 and 1970-01-01, and this is 621355968000000000. If you also take into account the timezone, the resulting code looks like this:

    function getTicks(date)
    {
        return ((date.getTime() - date.getTimezoneOffset() * 60000) * 10000) + 621355968000000000;
    }
    

现在,getTicks(new Date())将会得到与VB.Net中的Now.Ticks.ToString相同的结果,误差为1毫秒。


这个答案比被采纳的答案更简单易懂。使用一个简明易懂的表达式,而不是一个复杂的翻译。 - Jamie Thomas

4
var date = new Date();
var ticks = date.getTime();

getTime返回自1970年1月1日以来的毫秒数。


值得注意的是,这与毫秒以下的滴答声不同。 - Camilo Martin

1

如果精度不是问题,尝试使用TimeSpan.TicksPerMillisecond来表示您的计时器。


0

虽然不太好听,但这就是你需要的答案:http://codemonkey.joeuser.com/article/308527

DateTime.Ticks 表示自公元1年1月1日午夜12点以来已经过去的100纳秒间隔数。

JavaScript有Date.getTime()函数,它测量自1970年1月1日以来的毫秒数。因此,如果您只需要一个唯一的值,那么可以使用该函数。显然,这与DateTime.Ticks不能直接进行比较。


@Oppdal 这不是噩梦...只是加法和乘法。 - Camilo Martin

0

最快、最简单的版本是...

//get string version of time to the nearest millisecond
var now = "" + new Date().getTime();

//Though in most cases its easier to keep it as a number, and just concatinate in your output somewhere
document.title = "Now it is: " + new Date().getTime();

因为这个问题被标记为vb.net,并且vb.net有一个“强”语言提示,所以它被突出显示为vb.net。只是提供信息。您必须使用语言覆盖。http://meta.stackexchange.com/questions/82032/please-add-prettyprint-class-when-explicitly-defined-class-with-language/82042#82042 - Jeff Atwood
嗯,我现在明白“为什么”了... 但我认为这更像是可用性上的“回归”,而不是“功能”(因为它似乎以前就可以正常工作)。这个问题也被标记为 JavaScript(在这种情况下,期望的答案是 JavaScript)。是否有一个标记顺序来应用美化? - scunliffe
那么您应该从这个问题中删除[vb.net]标签。 - Jeff Atwood

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接