上都海奶茶馆 发表于 2017-2-22 10:12:09

nodejs中使用javascript的prototype特性进行日期格式化

  首先建立一个用来格式化日期的js文件dateFormat.js,内容如下:

[*]/**
[*] * Created by huopanpan on 2014/7/21.
[*] */
[*]functionMyDate(){
[*]Date.prototype.format =function(format)
[*]{
[*]var o ={
[*]"M+":this.getMonth()+1,//month
[*]"d+":this.getDate(),//day
[*]"h+":this.getHours(),//hour
[*]"m+":this.getMinutes(),//minute
[*]"s+":this.getSeconds(),//second
[*]"q+":Math.floor((this.getMonth()+3)/3),//quarter
[*]"S":this.getMilliseconds()//millisecond
[*]};
[*]if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
[*](this.getFullYear()+"").substr(4-RegExp.$1.length));
[*]for(var k in o)if(newRegExp("("+ k +")").test(format))
[*]            format = format.replace(RegExp.$1,
[*]RegExp.$1.length==1? o[k]:
[*]("00"+ o[k]).substr((""+ o[k]).length));
[*]return format;
[*]};
[*]}
[*]
[*]module.exports =MyDate;/导出该方法

    在上面代码中有一个MyDate函数,在函数中给Date的原型prototype中添加format函数,然后导出MyDate函数,或者可以将MyDate作为一个对象,只要能将其导出就行。

然后在代码中引入
var myDate = require('../models/utils/dateFormat');
此时myDate是一个函数,函数当然要执行了以后起内部的代码才起作用。所以我们可以再倒入以后让其自执行,就是在
var myDate = require('../models/utils/dateFormat')();
后面直接加括号,当然可以用myDate()这种方式来执行。执行以后Date对象中就有了format函数。我们在程序中如果需要对日期进行格式的时候就可以用这种方式来实现:
new Date().format("yyyy-MM-dd"),返回结果就是2014-07-12
页: [1]
查看完整版本: nodejs中使用javascript的prototype特性进行日期格式化