在項目中,常用時間進行格式化的輸出,以及轉換,同時作時間的統計,本來js原生的時間函數比較複雜繁瑣,不適合快速開發使用。npm
輕量級的moment.js很好的解決了這些問題。函數
下面以簡單的例子進行moment.js的調用。ui
一、安裝moment.js npm install momentspa
二、引用moment:prototype
var moment = require('moment');
三、進行調用:code
function writeFile(data, name) { fs.writeFile(path.join(__dirname, name + '.js'), 'module.exports =' + JSON.stringify(data), function (err) { if (err) throw err; console.log('Export' + name + ' Success!' + name + ' Export Time:', moment().format('YYYY-MM-DD HH:mm:ss')); }); }
從代碼中能夠看出,moment().format()便可進行快速的格式化輸出,moment.js提供多種格式。具體可參看API。orm
四、同時也能夠進行moment.js封裝,供其餘對象進行使用,代碼以下:對象
Util.prototype.toDateTimeString = function (timeStamp) { return toMoment(timeStamp).format('YYYY-MM-DD HH:mm:ss'); }; Util.prototype.toDateString = function (timeStamp) { return toMoment(timeStamp).format('YYYY-MM-DD'); }; Util.prototype.toTimeString = function (timeStamp) { return toMoment(timeStamp).format('HH:mm:ss'); }; function toMoment(timeStamp) { return moment(timeStamp * 1000); }
timeStamp爲具體的時間戳(時間戳(timestamp),一般是一個字符序列,惟一地標識某一刻的時間)。本文根據moment.js的相關API編寫,本人菜鳥一枚,若有不足之處,還請看官們見諒。