nodejs轻量级时间格式化组件Moment.js的使用例子

在项目中,常用时间进行格式化的输出,以及转换,同时作时间的统计,本来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编写,本人菜鸟一枚,若有不足之处,还请看官们见谅。
相关文章
相关标签/搜索