作家
登录

扩展javascript的Date方法实现代码(prototype)

作者: 来源:www.28hudong.com 2013-03-30 01:10:30 阅读 我要评论

最近项目的部分功能正在重构,前端也基本上推翻了原来的设计,在之前半年的积累上有了新的方案。这几天在做前端的重构和设计,遇到了一些问题。因为这个模块最主要的还是对时间的控制,大量的操作js的Date对象,可是js原生的Date方法太少了,操作起来太不方便。于是打算扩展下Date的prototype。 长期从事C#的开发,被C#影响着我的思维。C#中DateTime的操作就很方便,于是就参考它对js的Date做了扩展。 复制代码 代码如下: //将指定的毫秒数加到此实例的值上 Date.prototype.addMilliseconds = function (value) { var millisecond = this.getMilliseconds(); this.setMilliseconds(millisecond + value); return this; }; //将指定的秒数加到此实例的值上 Date.prototype.addSeconds = function (value) { var second = this.getSeconds(); this.setSeconds(second + value); return this; }; //将指定的分钟数加到此实例的值上 Date.prototype.addMinutes = function (value) { var minute = this.addMinutes(); this.setMinutes(minute + value); return this; }; //将指定的小时数加到此实例的值上 Date.prototype.addHours = function (value) { var hour = this.getHours(); this.setHours(hour + value); return this; }; //将指定的天数加到此实例的值上 Date.prototype.addDays = function (value) { var date = this.getDate(); this.setDate(date + value); return this; }; //将指定的星期数加到此实例的值上 Date.prototype.addWeeks = function (value) { return this.addDays(value * 7); }; //将指定的月份数加到此实例的值上 Date.prototype.addMonths = function (value) { var month = this.getMonth(); this.setMonth(month + value); return this; }; //将指定的年份数加到此实例的值上 Date.prototype.addYears = function (value) { var year = this.getFullYear(); this.setFullYear(year + value); return this; }; //格式化日期显示 format="yyyy-MM-dd hh:mm:ss"; 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; } 使用方法我想应该不用多说了,就是: 复制代码 代码如下: var date = new Date(); date.addHours(1); date.addYears(2); document.write(date.format('yyyy-MM-dd hh:mm:ss')); 希望这个扩展方法可以帮助到大家。

  推荐阅读

  JQuery 选择和过滤方法代码总结

1、查找所有符合条件的元素 find() 举例: $('ul').find('li').addClass('tmpExample'); 查找页面中ul元素下的所有li元素,并为查找到的li元素增加tmpExample样式。 2、查找指定元素的兄弟节点 >>>详细阅读


本文标题:扩展javascript的Date方法实现代码(prototype)

地址:http://www.17bianji.com/kaifa2/JS/25383.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)