给Date原型附加format函数支持格式化输出
来源:互联网 发布:世界人工智能大会2017 编辑:程序博客网 时间:2024/06/06 12:48
代码一:
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 (new RegExp("(" + k + ")").test(format))format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]: ("00" + o[k]).substr(("" + o[k]).length));return format;}
代码二:
Date.prototype.format = function(pattern) {var returnValue = pattern;var format = {"y+" : this.getFullYear(),"M+" : this.getMonth() + 1,"d+" : this.getDate(),"H+" : this.getHours(),"m+" : this.getMinutes(),"s+" : this.getSeconds(),"S" : this.getMilliseconds()};for ( var key in format) {var regExp = new RegExp("(" + key + ")");if (regExp.test(returnValue)) {var zero = "";var replacement = null;for ( var i = 0; i < RegExp.$1.length; i++) {zero += "0";}if (RegExp.$1.length == 1) {replacement = format[key];} else {replacement = (zero + format[key]).substring((("" + format[key]).length));}returnValue = returnValue.replace(RegExp.$1, replacement);}}return returnValue;};
var dateStr = "2014-09-08";var arr = dateStr.split("-");var date = new Date(Number(arr[0]), Number(arr[1])-1, Number(arr[2]));date.format("M.d");
输出结果:"9.8"
以上在IE8和Chrome测试通过。源地址:http://www.blogjava.net/mixer-a/archive/2012/05/10/377846.html
另外说点浏览器差异:
parseInt("08");// 执行结果ie8下为0,chrome下为8new Date("2014-08-6");// 执行结果ie8下undefined,chrome下成功创建日期Date对象
0 0
- 给Date原型附加format函数支持格式化输出
- 格式化输出函数: Format
- 格式化输出函数(1): Format
- Date() 时间的一个 format 格式化函数
- python输出格式化及函数format
- python输出格式化及函数format
- python输出格式化及函数format
- python输出格式化及函数format
- python输出格式化及函数format
- python输出格式化及函数format
- python格式化输出函数之format
- date.format,日期格式化
- JS关于Date函数的格式化输出
- 在mysql中,DATE_FORMAT(date, format) 函数根据format字符串格式化date值。
- erlang: format 格式化输出
- 格式化format()输出字符串
- String.format() (格式化输出)
- python-格式化输出-format
- Duanxx的HEVC学习(三)HEVC编码框架(三)帧间预测
- easyui data-options的使用
- LeetCode OJ算法题(四十六):Permutation II
- Heavy Cargo(数论)
- java Atomic 包实现
- 给Date原型附加format函数支持格式化输出
- 遍历所有桌面子窗口
- UVa 679 Dropping Balls
- poj 3026 Borg Maze bfs+prim
- android布局常用属性介绍
- 对json中时间格式的处理
- 解决aapt.exe停止工作(No resource identifier found for attribute 'showAsAction' in package 'android')
- java连接mysql,测试通过
- 刻录光盘