nodejs輕量級時間格式化組件Moment.js的使用例子


在項目中,經常使用時間進行格式化的輸出,以及轉換,同時做時間的統計,原本js原生的時間函數比較復雜繁瑣,不適合快速開發使用。

輕量級的moment.js很好的解決了這些問題。

下面以簡單的例子進行moment.js的調用。

1、安裝moment.js    npm install moment

2、引用moment:

var moment = require('moment');

3、進行調用:

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。

4、同時也可以進行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編寫,本人
菜鳥一枚,如有不足之處,還請看官們見諒。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM