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
.
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.
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;
}
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);