如何将刻度转换为 momentjs 对象

how to convert ticks to momentjs object

我正在使用 nodatime,它 returns 滴答作响。如何使用 momentjs 转换刻度以使用和格式化?

public JsonResult Foo()
{
  var now = SystemClock.Instance.Now.Ticks;
  return Json(now, JsonRequestBehavior.AllowGet);
}

它returnslong比如14598788048897648.

Moment.js 没有直接接受报价的构造函数,但是它确实有 one that accepts the number of milliseconds that have elapsed since the epoch,这可能适合这个:

// Dividing your ticks by 10000 will yield the number of milliseconds
// as there are 10000 ticks in a millisecond
var now = moment(ticks / 10000);

This GitHub discussion in the NodaTime repository 讨论了使用扩展方法来支持此行为以及 return 服务器端代码的毫秒数:

public static long ToUnixTimeMilliseconds(this Instant instant)
{
    return instant.Ticks / NodaConstants.TicksPerMillisecond;
}

根据 the documentation,Instant.Ticks 属性 是:

The number of ticks since the Unix epoch.

而且,

A tick is equal to 100 nanoseconds. There are 10,000 ticks in a millisecond.

Date 对象在其构造函数中获取自 Unix 纪元以来的毫秒数,并且由于 moment 在幕后使用 Date 构造函数,您可以只使用:

var value = moment(ticks/10000);

不要从 API 中泄漏 Ticks。相反,使用 NodaTime.Serialization.JsonNet 包允许像 Instant 这样的 NodaTime 类型以 ISO8601 标准格式序列化。 moment.js.

本机支持该格式

查看页面底部的 the user guide page on serialization