将C#.NET DateTime.ticks转换为JavaScript中的天/小时/分钟

Cia*_*her 10 .net javascript c# datetime

在我的系统中,我在Ticks中存储一个持续时间,这个持续时间被传递给我的客户端移动应用程序,并且从那里我想将ticks转换为人类可读的形式.在我的情况下,天,小时和分钟.

我的客户端移动应用程序是使用Javascript编码的,所以这就是我用来将持续时间转换为天/小时/分钟的方法.

Cia*_*her 9

在C#.NET中,单个刻度表示一百纳秒,或一千万分之一秒.[来源].

因此,为了计算从滴答数(舍入到最接近的整数)的天数,我首先计算乘以一千万的秒数,然后乘以一天中的秒数(60)以分钟为单位,每小时60分钟,每天24小时).我使用模数运算符(%)来获得构成小时和分钟持续时间的余数值.

var time = 3669905128; // Time value in ticks
var days = Math.floor(time/(24*60*60*10000000)); // Math.floor() rounds a number downwards to the nearest whole integer, which in this case is the value representing the day
var hours = Math.round((time/(60*60*10000000)) % 24); // Math.round() rounds the number up or down
var mins = Math.round((time/(60*10000000)) % 60);

console.log('days: ' + days);   
console.log('hours: ' + hours);   
console.log('mins: ' + mins);
Run Code Online (Sandbox Code Playgroud)

因此,在上面的例子中,刻度数相当于6分钟(向上舍入).

再举一个例子,我们获得了2538天,15小时和23分钟的票数为2,193,385,800,000,000.

  • 请使用`10e7`而不是`10000000`,这是指数表示法有用的! (5认同)
  • 10e7 在 1 之后有 8 个零。10000000 实际上是 10e6 :) (2认同)

pkm*_*337 6

var ticks = 635556672000000000; 

//ticks are in nanotime; convert to microtime
var ticksToMicrotime = ticks / 10000;

//ticks are recorded from 1/1/1; get microtime difference from 1/1/1/ to 1/1/1970
var epochMicrotimeDiff = Math.abs(new Date(0, 0, 1).setFullYear(1));

//new date is ticks, converted to microtime, minus difference from epoch microtime
var tickDate = new Date(ticksToMicrotime - epochMicrotimeDiff);
Run Code Online (Sandbox Code Playgroud)

根据此页面,setFullYear方法返回"A Number,表示日期对象与1970年1月1日午夜之间的毫秒数".

查看此页面,了解javascript Date对象中的所有方法.