how to convert ticks to momentjs object

試著忘記壹切 提交于 2019-12-24 00:15:51

问题


I'm using nodatime and it returns ticks. How can I convert ticks to use and format using momentjs?

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

it returns long such as 14598788048897648.


回答1:


Don't leak Ticks out of your API. Instead, use the NodaTime.Serialization.JsonNet package to allow NodaTime types like Instant to be serialized in ISO8601 standard format. That format is supported natively in moment.js.

See the user guide page on serialization, towards the bottom of the page.




回答2:


Moment.js doesn't have a constructor that directly accepts ticks, however it does have one that accepts the number of milliseconds that have elapsed since the epoch, which might be suitable for this :

// 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 discusses the use of an extension method to support this behavior as well to return the number of milliseconds from your server-side code :

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



回答3:


According to the documentation, the Instant.Ticks property is:

The number of ticks since the Unix epoch.

And,

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

A Date object takes the number of milliseconds since the Unix epoch in its constructor, and since moment uses the Date constructor underneath the covers, you can just use:

var value = moment(ticks/10000);


来源:https://stackoverflow.com/questions/36555596/how-to-convert-ticks-to-momentjs-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!