2017-08-01 47 views
2

我使用moment.js來獲得相對時間。例如,它返回「6小時前」。但我想獲得像「6h」這樣的短版。如何更改fromNow調用的輸出?

我讀的文檔:http://momentjs.com/docs/#/customization/relative-time/

但是,如果我改變:

moment.updateLocale('en', { 
    relativeTime : { 
     future: "in %s", 
     past: "%s ago", 
     s : 'a few seconds', 
     ss : '%d seconds', 
     m: "a minute", 
     mm: "%d minutes", 
     h: "an hour", 
     hh: "%d hours", 
     d: "a day", 
     dd: "%d days", 
     M: "a month", 
     MM: "%d months", 
     y: "a year", 
     yy: "%d years" 
    } 
}); 

moment.updateLocale('en', { 
    relativeTime : { 
     future: "in %s", 
     past: "%s", 
     s : 'a few seconds', 
     ss : '%d h', 
     m: "a minute", 
     mm: "%d m", 
     h: "an hour", 
     hh: "%d h", 
     d: "a day", 
     dd: "%d d", 
     M: "a month", 
     MM: "%d m", 
     y: "a year", 
     yy: "%d y" 
    } 
}); 

我得到的錯誤:

Cannot read property 'humanize' of undefined at Moment.from (moment.js:3313)

當我打電話

moment(value).fromNow() 

這裏,值是一個日期,日期型

是否有可能獲得短格式版本moment.js?

+0

所以,你不與第一對象得到錯誤? –

+0

另外,你使用的是什麼版本的Moment.js? –

+0

我使用2.18.1 –

回答

1

我假設你的問題是格式字符串。我用 'HH':

moment.updateLocale('en', { 
 
    relativeTime : { 
 
     future: "in %s", 
 
     past: "%s ago", 
 
     s : 'a few seconds', 
 
     ss : '%d seconds', 
 
     m: "a minute", 
 
     mm: "%d minutes", 
 
     h: "an hour", 
 
     hh: "%dh", 
 
     d: "a day", 
 
     dd: "%d days", 
 
     M: "a month", 
 
     MM: "%d months", 
 
     y: "a year", 
 
     yy: "%d years" 
 
    } 
 
}); 
 

 
// 
 
// compute six hours ago... 
 
// 
 
var value = new Date(); 
 
value.setHours(value.getHours() - 6); 
 

 

 
console.log('With \'hh\' format string: ' + moment(value).fromNow('hh')); 
 
console.log('With no format: ' + moment(value).fromNow());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

+0

哼,我想使用fromNow withtout'hh',因爲有時它應該是4d。所以,我不能從現在的方法給鑰匙。 –

+1

我解決了我過去的問題:「%s」,而不是過去:「%s前」,並調用fromNow(false) –