2016-04-11 23 views
1

我正在使用nodatime並返回刻度。如何將tick轉換爲使用momentjs進行使用和格式化?如何將刻度轉換爲momentjs對象

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

返回long14598788048897648

回答

3

不漏Ticks超出你的API。相反,使用NodaTime.Serialization.JsonNet包允許按照ISO8601標準格式序列化Instant等NodaTime類型。該格式在moment.js中得到本地支持。

請參閱the user guide page on serialization,朝向頁面的底部。

+0

你認爲你可以做一個代碼演示如何使用它?備查。 –

+0

如果只是這一種方法,你也可以直接調用'.ToDateTimeUtc()'並讓默認的序列化器完成它的工作。 –

+0

我明白了。但是,例如我使用上面相同的代碼將其轉換爲其他'DateTimeZoneProvider'。我仍然可以使用'ToDateTimeUtc()'返回的值轉換爲其他提供者嗎? –

3

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討論了使用擴展方法來支持這種行爲以及從服務器端代碼返回毫秒數:

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

其實,你的答案很好,它只是使用標準格式而不是蜱。 –

+0

它看起來像前一連串的評論被刪除。我在[Hanselminutes討論NodaTime和Moment.js](http://hanselminutes.com/485/the-problem-with-datetime-nodatime-with-matt-johnson)上聽了你的意見,所以我想你知道關於這些庫中的任何一個都比我做的要多得多,並且知道什麼時候什麼可以起作用。 –

+0

是的,我回想起0001的'SystemTimeTime'時代,但是NodaTime使用1970和JS一樣的時刻。乾杯! –

0

the documentation,在Instant.Ticks屬性是:

自Unix紀元以來的刻度數。

而且,

Tick是等於100納秒。毫秒中有10,000個刻度。

一個Date對象,採取的毫秒數,因爲在其構造Unix紀元,由於時刻使用Date構造蓋的下面,你可以使用:

var value = moment(ticks/10000);