实现JavaScript中Date对象的format()函数
2015-03-26 16:12
645 查看
因Web页面展示问题,经常需要将日期转换为某种格式,但是JavaScript脚本语言官方却没有对其提供,程序员都很懒的,咱们自个来写,自个来扩展!!
其实这个还可以优化,但是时间问题,我这就不改动了,大家有兴趣的可以在评论中重写
/** * Author Joyce.Luo 11:57:35 prepared in 2015.02.10 * JavaScript language Methods: format(), based on the replace() method to realize * For example: * new Date().format("yyyy-MM-dd HH:mm:ss"); * new Date().format("yyyy-MM-dd"); * @param {} pattern the pattern describing the date and time format * @return {} returns a formatted string date */ Date.prototype.format = function(pattern){ var o = { "M+" : this.getMonth()+1, /*Month*/ "d+" : this.getDate(), /*Day*/ "h+" : this.getHours(), /*Hours*/ "m+" : this.getMinutes(), /*Minute*/ "s+" : this.getSeconds(), /*Seconds*/ "q+" : Math.floor((this.getMonth()+3)/3), /*Quarter*/ "S" : this.getMilliseconds() /*Millisecond*/ }; if (/(y+)/.test(pattern)) pattern = pattern.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(pattern)) pattern = pattern.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return pattern; }
其实这个还可以优化,但是时间问题,我这就不改动了,大家有兴趣的可以在评论中重写
相关文章推荐
- JavaScript---对象学习(二)Array对象、Date对象及其重要函数学习
- javascript中Date对象与函数
- 实现JavaScript中String对象的replaceAll()函数
- 扩展javascript date对象增加format
- JavaScript实现格式化字符串函数String.format
- 给 Javascript 的 日期(Date)对象扩展一个格式化(format)方法
- javascript下Date对象的时间格式化函数
- javascript学习 - js的Date对象函数
- 对 meizz javascript date format 日期格式化函数的增强和改写
- JavaScript Date 对象与函数
- javascript用arguments数组对象实现参数变量可变的函数
- javascript用函数实现对象的方法
- javascript 函数 Date对象 数组对象
- JavaScript Date对象 日期获取函数
- javascript用函数实现对象
- 常见对象_DateFormat实现日期和字符串的相互转换
- JavaScript下的时间格式处理函数Date.prototype.format
- javascript Date Format 函数
- JavaScript 实现格式化字符串函数String.format (解决引号嵌套转义符问题)
- javascript下Date对象的时间格式化函数