`
start_p
  • 浏览: 65281 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

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

阅读更多

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

  1. /**
  2. * Created by huopanpan on 2014/7/21.
  3. */
  4. functionMyDate(){
  5. Date.prototype.format =function(format)
  6. {
  7. var o ={
  8. "M+":this.getMonth()+1,//month
  9. "d+":this.getDate(),//day
  10. "h+":this.getHours(),//hour
  11. "m+":this.getMinutes(),//minute
  12. "s+":this.getSeconds(),//second
  13. "q+":Math.floor((this.getMonth()+3)/3),//quarter
  14. "S":this.getMilliseconds()//millisecond
  15. };
  16. if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
  17. (this.getFullYear()+"").substr(4-RegExp.$1.length));
  18. for(var k in o)if(newRegExp("("+ k +")").test(format))
  19. format = format.replace(RegExp.$1,
  20. RegExp.$1.length==1? o[k]:
  21. ("00"+ o[k]).substr((""+ o[k]).length));
  22. return format;
  23. };
  24. }
  25. 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
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics