本篇文章给大家带来的内容是关于js的date处理函数如何进行扩展?js中data函数的扩展方法,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
背景:
js 有自己的 时间类型 date —— 但是,在某些情况下 这个对象似乎 不太好用。
本文 基于 jquery 扩展了一些 js日期函数,包括:
> 字符串 转 date 对象 万能函数(性能仅 10w次/s,函数有路径优化,字符串越诡异 耗时越长)
> date 转 字符串 格式化
> 两个 date 的差值 (返回的结果类似 c# timespan 对象)
一言不合,直接上代码:
/*感谢 inkfx (c) http://www.ink-fx.com 为 以下日期函数 作出的努力 */jquery = window.jquery || { };(function($) { /*--数据类型转换函数 start----------------------------------*/ $.isarray = function(obj) {var result = false;try {result = object.prototype.tostring.apply(obj) === '[object array]';if (result) return true;} catch(e) {}try {result = obj.constructor === array;if (result) return true;} catch(e) {}return false;}; $.toint = function(obj, dft) {try {dft = (typeof dft === 'number') ? dft : 0;} catch(e) {dft = 0;}try {if (obj == null) return dft;if (typeof obj === 'number') return parseint(obj);var match = obj.tostring().tolowercase().match(/-*[0123456789abcdefx.]+/);var str = match == null || match.length <= 0 ? null : match[0];var result = null;if (str != null && str.length >= 2 && str.substr(0, 2) == "0x") {str = str.substr(2);result = parseint(str, 16);} else {result = parseint(str);}if (result == null || !isfinite(result)) return dft;return result;} catch(e) {return dft;}}; $.tofloat = function(obj, dft) {try {dft = (typeof dft === 'number') ? dft : 0;} catch(e) {dft = 0;}try {if (obj == null) return dft;if (typeof obj === 'number') return parsefloat(obj);var match = obj.tostring().tolowercase().match(/-*[0123456789abcdefx.]+/);var str = match == null || match.length <= 0 ? null : match[0];var result = null;if (str != null && str.length >= 2 && str.substr(0, 2) == "0x") {str = str.substr(2);result = parsefloat(parseint(str, 16));} else {result = parsefloat(str);}if (result == null || !isfinite(result)) return dft;return result;} catch(e) {return dft;}}; $.tostring = function(obj, dft) {try {dft = (typeof dft === 'string') ? dft : '';} catch(e) {dft = '';}try {if (obj == null) return dft;if (typeof obj === 'string') return obj;return obj.tostring();} catch(e) {return dft;}}; $.todatetime = function(obj, dft) {try {dft = (dft instanceof date) ? dft : new date(1900, 00, 01);} catch(e) {dft = new date(1900, 00, 01);}try {if (obj == null) return dft;if (obj instanceof date) return obj;var result = parsedate(obj);if (result == null) return dft;return result;} catch(e) {return dft;}}; $.toboolean = function(obj, dft) {try {dft = (typeof dft === 'boolean') ? dft : false;} catch(e) {dft = false;}try {if (obj == null) return dft;if (obj == true) return true;if (obj == false) return false;if ($.isarray(obj)) return obj.length >= 1;if (typeof obj === 'boolean') return obj.tostring().tolowercase() == "true";if (typeof obj === 'number') return parsefloat(obj) > 0;/*if (typeof obj === 'string') return parsefloat(obj) > 0;*/if (obj.tostring().tolowercase() == "t") return true;if (obj.tostring().tolowercase() == "true") return true;return false;} catch(e) {return dft;}}; /*--数据类型转换函数 end------------------------------------*/ /*--时间相关函数 start--------------------------------------*/ $.formatdate = function(date, fmt) {try {date = $.todatetime(date);fmt = fmt || "yyyy-mm-dd hh:mm:ss"; o = {"m+": date.getmonth() + 1,"d+": date.getdate(),"h+": date.gethours(),"h+": date.gethours() /*(date.gethours() > 12 ? (date.gethours() - 12) : date.gethours())*/,"m+": date.getminutes(),"s+": date.getseconds(),"q+": math.floor((date.getmonth() + 3) / 3),"s": date.getmilliseconds(),"f+": date.getmilliseconds()};if (/(y+)/.test(fmt)) fmt = fmt.replace(regexp.$1, (date.getfullyear() + "").substr(4 - regexp.$1.length));for (var k in o)if (new regexp("(" + k + ")").test(fmt)) {var padleft = (k == "s" || k == "f+") ? "000" : "00";fmt = fmt.replace(regexp.$1, regexp.$1.length == 1 ? o[k] : (padleft + o[k]).substr(("" + o[k]).length));}return fmt;} catch(e) { return ""; }}; $.isleapyeardate = function(date) {try {date = $.todatetime(date);return (0 == date.getfullyear() % 4 && ((date.getfullyear() % 100 != 0) || (date.getfullyear() % 400 == 0)));} catch(e) {return false;}}; $.addyears = function(date, num) {try {date = $.todatetime(date);num = $.toint(num);var year = date.getfullyear();var month = date.getmonth();var day = date.getdate();var hour = date.gethours();var minute = date.getminutes();var second = date.getseconds();var millisecond = date.getmilliseconds();var result = new date(year + num, month, day, hour, minute, second, millisecond);return result;} catch(e) { return new date(1900, 01, 01); }}; $.addmonths = function(date, num) {try {date = $.todatetime(date);num = $.toint(num);var year = date.getfullyear();var month = date.getmonth();var day = date.getdate();var hour = date.gethours();var minute = date.getminutes();var second = date.getseconds();var millisecond = date.getmilliseconds();var addyear = (num + month) / 12;month = (num + month) % 12;var result = new date(year + addyear, month, day, hour, minute, second, millisecond);return result;} catch(e) { return new date(1900, 01, 01); }}; $.adddays = function(date, num) {try {date = $.todatetime(date);num = $.toint(num);var result = new date(date.valueof() + (num * 1000 * 60 * 60 * 24));return result;} catch(e) { return new date(1900, 01, 01); }}; $.addhours = function(date, num) {try {date = $.todatetime(date);num = $.toint(num);var result = new date(date.valueof() + (num * 1000 * 60 * 60));return result;} catch(e) { return new date(1900, 01, 01); }}; $.addminutes = function(date, num) {try {date = $.todatetime(date);num = $.toint(num);var result = new date(date.valueof() + (num * 1000 * 60));return result;} catch(e) { return new date(1900, 01, 01); }}; $.addseconds = function(date, num) {try {date = $.todatetime(date);num = $.toint(num);var result = new date(date.valueof() + (num * 1000));return result;} catch(e) { return new date(1900, 01, 01); }}; $.addmilliseconds = function(date, num) {try {date = $.todatetime(date);num = $.toint(num);var result = new date(date.valueof() + num);return result;} catch(e) { return new date(1900, 01, 01); }}; $.gettimespan = function(date1, date2) {var timestamp = 0;if((date1 instanceof date || date2 instanceof date || date2 == null) || (date1 != null && date2 != null)) {date1 = $.todatetime(date1);date2 = $.todatetime(date2);timestamp = $.tofloat(date1 - date2);} else {timestamp = $.toint(date1);}var temp = $.toint(timestamp / 1000);var totalmillisecond = timestamp;var totalsecond = timestamp / (1000);var totalminute = timestamp / (1000 * 60);var totalhour = timestamp / (1000 * 60 * 60);var totalday = timestamp / (1000 * 60 * 60 * 24);var millisecond = $.toint(totalmillisecond) % 1000;var second = $.toint(totalsecond) % 60;var minute = $.toint(totalminute) % 60;var hour = $.toint(totalhour) % 24;var day = $.toint(totalday);return {timestamp: timestamp,days: day,hours: hour,minutes: minute,seconds: second,milliseconds: millisecond,totaldays: totalday,totalhours: totalhour,totalminutes: totalminute,totalseconds: totalsecond,totalmilliseconds: totalmillisecond,valueof: function() { return this.timestamp; },tostring: function() { return this.days + "." + $.padleft(this.hours, 2, "0") + ":" + $.padleft(this.minutes, 2, "0") + ":" + $.padleft(this.seconds, 2, "0") + "." + $.padleft(this.milliseconds, 3, "0"); } };} /*--时间相关函数 end----------------------------------------*/})(jquery);
代码比较长,当时我写完之后,顺手就把 js压缩了。
代码调用如下:
var begin = new date(); //执行15w次 自动识别转换: //i3 cpu //chrome: 5秒 平均: 30000次/s //ie 9 : 26秒 平均: 5770次/s //i5 cpu //chrome: 14秒 20*100000次 平均: 107000次/s for (var i = 0; i < 10000; i++) { var result1 = $.todatetime("2017-03-19 01:43:15 123453"); var result2 = $.todatetime("2017-03-19t01:43:15 123453"); var result3 = $.todatetime("2017-03-19"); var result4 = $.todatetime("2017/03/19 01:43:15"); var result5 = $.todatetime("03/19/2017 01:43:15"); var result6 = $.todatetime("03/19/2017 01:43"); var result7 = $.todatetime("01:43:15 123453"); var result8 = $.todatetime("01:43:15.123453"); var result9 = $.todatetime("01:43:15"); var result10 = $.todatetime("01:43"); var result11 = $.todatetime("2017/03/19"); var result12 = $.todatetime("03/19/2017"); var result13 = $.todatetime("mon mar 20 2017 02:46:06 gmt+0800 (中国标准时间)"); var result14 = $.todatetime("mon mar 20 02:46:06 utc+0800 2017"); var result15 = $.todatetime("mon mar 20 2017 02:46:06"); var result16 = $.todatetime("2017年3月19日 01时43分15秒"); var result17 = $.todatetime("2017年03月19日01:43:15"); var result18 = $.todatetime("2017年03月19日 01:43"); var result19 = $.todatetime("2017年03月19日"); var result20 = $.todatetime("1时43分15秒"); } var end = new date(); document.writeln( "计算 " + (i) + "*20次, 耗时:" + "<br/>" + begin.format("yyyy-mm-dd hh:mm:ss fff") + "<br/>" + end.format("yyyy-mm-dd hh:mm:ss fff") + "<br/>" + "计算结果: " + "<br/> $.todatetime(\"2017-03-19 01:43:15 123453\") >> " + result1.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"2017-03-19t01:43:15 123453\") >> " + result2.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"2017-03-19\") >> " + result3.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"2017/03/19 01:43:15\") >> " + result4.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"03/19/2017 01:43:15\") >> " + result5.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"03/19/2017 01:43\") >> " + result6.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"01:43:15 123453\") >> " + result7.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"01:43:15.123453\") >> " + result8.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"01:43:15\") >> " + result9.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"01:43\") >> " + result10.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"2017/03/19\") >> " + result11.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"03/19/2017\") >> " + result12.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"mon mar 20 2017 02:46:06 gmt+0800 (中国标准时间)\") >> " + result13.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"mon mar 20 02:46:06 utc+0800 2017\") >> " + result14.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"mon mar 20 2017 02:46:06\") >> " + result15.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"2017年3月19日 01时43分15秒\") >> " + result16.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"2017年03月19日01:43:15\") >> " + result17.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"2017年03月19日 01:43\") >> " + result18.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"2017年03月19日\") >> " + result19.format("yyyy-mm-dd hh:mm:ss fff") + "<br/> $.todatetime(\"1时43分15秒\") >> " + result20.format("yyyy-mm-dd hh:mm:ss fff") );
上面的代码中:
"mon mar 20 2017 02:46:06 gmt+0800 (中国标准时间)""mon mar 20 02:46:06 utc+0800 2017""mon mar 20 2017 02:46:064 这三种,分别是 chrome firefox ie 的 date 对象 tostring() 的结果。万能函数 也已经进行了反向解析支持。
ps.
看客不禁哈哈大笑:“除非有bug,否则这种 date.tostring() 的字符串 根本就不该出现在程序中。”
如果您觉得 这三种 字符串类型 不会出现。
—— 那我们看看 大名鼎鼎的 element-ui 库中,datepicker 控件 是如何 闹心的:
http://element-cn.eleme.io/1.4/#/zh-cn/component/date-picker
http://element-cn.eleme.io/2.4/#/zh-cn/component/date-picker (新版已经修正了bug)
无一例外:控件的值 不能直接获取,只能通过 change 事件取值。如何获取时间差:
var timespan = $.gettimespan("2017-03-27 21:20:05 000", "2017-03-25 10:10:10 000");alert(timespan); //日期比较 是可以直接使用 > < 的alert(timespan.totaldays); //两个时间相差的天数(有小数,比如 1.5天)alert(timespan.totalhours); //两个时间相差的小时数(有小数)alert(timespan.totalminutes); //两个时间相差的分钟数(有小数)alert(timespan.totalseconds); //两个时间相差的秒数(有小数)alert(timespan.totalmilliseconds); //两个时间相差的毫秒数(有小数)alert($.addyears("2017-03-27 21:20:05 123456", 5)); //在指定时间基础上,增加 5 年alert($.addmonths("2017-03-27 21:20:05 123456", 48)); //在指定时间基础上,增加 48 月alert($.adddays("2017-03-27 21:20:05 123456", 365)); //在指定时间基础上,增加 365 天alert($.addhours("2017-03-27 21:20:05 123456", 48)); //在指定时间基础上,增加 48 消失alert($.addminutes("2017-03-27 21:20:05 123456", 120)); //在指定时间基础上,增加 120分钟alert($.addseconds("2017-03-27 21:20:05 123456", 480)); //在指定时间基础上,增加 480秒alert($.addmilliseconds("2017-03-27 21:20:05 123456", 10300)); //在指定时间基础上,增加 10300毫秒
是的, js 的 date 对象, 好多你需要但是 底层不提供的 函数 —— 本文 都已经提供。
相关推荐:
php变量与类型扩展之函数处理及变量处理
js字符串函数扩展代码_javascript技巧
以上就是js的date处理函数如何进行扩展?js中data函数的扩展方法的详细内容。
