웹 프론트엔드 JS 튜토리얼 JS의 날짜 처리 기능을 확장하는 방법은 무엇입니까? js의 데이터 함수 확장 방법

JS의 날짜 처리 기능을 확장하는 방법은 무엇입니까? js의 데이터 함수 확장 방법

Aug 17, 2018 pm 03:54 PM

本篇文章给大家带来的内容是关于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 === &#39;number&#39;) ? dft : 0;} catch(e) {dft = 0;}try {if (obj == null) return dft;if (typeof obj === &#39;number&#39;) 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 === &#39;number&#39;) ? dft : 0;} catch(e) {dft = 0;}try {if (obj == null) return dft;if (typeof obj === &#39;number&#39;) 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 === &#39;string&#39;) ? dft : &#39;&#39;;} catch(e) {dft = &#39;&#39;;}try {if (obj == null) return dft;if (typeof obj === &#39;string&#39;) 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 === &#39;boolean&#39;) ? 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 === &#39;boolean&#39;) return obj.toString().toLowerCase() == "true";if (typeof obj === &#39;number&#39;) return parseFloat(obj) > 0;/*if (typeof obj === &#39;string&#39;) 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의 날짜 처리 기능을 확장하는 방법은 무엇입니까? js의 데이터 함수 확장 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

내 자신의 JavaScript 라이브러리를 어떻게 작성하고 게시합니까? 내 자신의 JavaScript 라이브러리를 어떻게 작성하고 게시합니까? Mar 18, 2025 pm 03:12 PM

기사는 JavaScript 라이브러리 작성, 게시 및 유지 관리, 계획, 개발, 테스트, 문서 및 홍보 전략에 중점을 둡니다.

브라우저에서 성능을 위해 JavaScript 코드를 최적화하려면 어떻게해야합니까? 브라우저에서 성능을 위해 JavaScript 코드를 최적화하려면 어떻게해야합니까? Mar 18, 2025 pm 03:14 PM

이 기사는 브라우저에서 JavaScript 성능을 최적화하기위한 전략에 대해 설명하고 실행 시간을 줄이고 페이지로드 속도에 미치는 영향을 최소화하는 데 중점을 둡니다.

프론트 엔드 열 용지 영수증에 대한 차량 코드 인쇄를 만나면 어떻게해야합니까? 프론트 엔드 열 용지 영수증에 대한 차량 코드 인쇄를 만나면 어떻게해야합니까? Apr 04, 2025 pm 02:42 PM

프론트 엔드 개발시 프론트 엔드 열지대 티켓 인쇄를위한 자주 묻는 질문과 솔루션, 티켓 인쇄는 일반적인 요구 사항입니다. 그러나 많은 개발자들이 구현하고 있습니다 ...

브라우저 개발자 도구를 사용하여 JavaScript 코드를 효과적으로 디버그하려면 어떻게해야합니까? 브라우저 개발자 도구를 사용하여 JavaScript 코드를 효과적으로 디버그하려면 어떻게해야합니까? Mar 18, 2025 pm 03:16 PM

이 기사는 브라우저 개발자 도구를 사용하여 효과적인 JavaScript 디버깅, 중단 점 설정, 콘솔 사용 및 성능 분석에 중점을 둡니다.

소스 맵을 사용하여 조정 된 JavaScript 코드를 디버그하는 방법은 무엇입니까? 소스 맵을 사용하여 조정 된 JavaScript 코드를 디버그하는 방법은 무엇입니까? Mar 18, 2025 pm 03:17 PM

이 기사는 소스 맵을 사용하여 원래 코드에 다시 매핑하여 미니어링 된 JavaScript를 디버그하는 방법을 설명합니다. 소스 맵 활성화, 브레이크 포인트 설정 및 Chrome Devtools 및 Webpack과 같은 도구 사용에 대해 설명합니다.

Java의 컬렉션 프레임 워크를 효과적으로 사용하려면 어떻게해야합니까? Java의 컬렉션 프레임 워크를 효과적으로 사용하려면 어떻게해야합니까? Mar 13, 2025 pm 12:28 PM

이 기사는 Java의 컬렉션 프레임 워크의 효과적인 사용을 탐구합니다. 데이터 구조, 성능 요구 및 스레드 안전을 기반으로 적절한 컬렉션 (목록, 세트, ​​맵, 큐)을 선택하는 것을 강조합니다. 효율적인 수집 사용을 최적화합니다

초보자를위한 타이프 스크립트, 2 부 : 기본 데이터 유형 초보자를위한 타이프 스크립트, 2 부 : 기본 데이터 유형 Mar 19, 2025 am 09:10 AM

엔트리 레벨 타입 스크립트 자습서를 마스터 한 후에는 TypeScript를 지원하고 JavaScript로 컴파일하는 IDE에서 자신의 코드를 작성할 수 있어야합니다. 이 튜토리얼은 TypeScript의 다양한 데이터 유형으로 뛰어납니다. JavaScript에는 NULL, UNDEFINED, BOOLEAN, 번호, 문자열, 기호 (ES6에 의해 소개 됨) 및 객체의 7 가지 데이터 유형이 있습니다. TypeScript는이 기반으로 더 많은 유형을 정의 하며이 튜토리얼은이 모든 튜토리얼을 자세히 다룹니다. 널 데이터 유형 JavaScript와 마찬가지로 Null in TypeScript

Chart.js : Pie, Donut 및 Bubble Charts를 시작합니다 Chart.js : Pie, Donut 및 Bubble Charts를 시작합니다 Mar 15, 2025 am 09:19 AM

이 튜토리얼은 Chart.js를 사용하여 파이, 링 및 버블 차트를 만드는 방법을 설명합니다. 이전에는 차트 유형의 차트 유형을 배웠습니다. JS : 라인 차트 및 막대 차트 (자습서 2)와 레이더 차트 및 극지 지역 차트 (자습서 3)를 배웠습니다. 파이 및 링 차트를 만듭니다 파이 차트와 링 차트는 다른 부분으로 나뉘어 진 전체의 비율을 보여주는 데 이상적입니다. 예를 들어, 파이 차트는 사파리에서 남성 사자, 여성 사자 및 젊은 사자의 비율 또는 선거에서 다른 후보자가받는 투표율을 보여주는 데 사용될 수 있습니다. 파이 차트는 단일 매개 변수 또는 데이터 세트를 비교하는 데만 적합합니다. 파이 차트의 팬 각도는 데이터 포인트의 숫자 크기에 의존하기 때문에 원형 차트는 값이 0 인 엔티티를 그릴 수 없습니다. 이것은 비율이 0 인 모든 엔티티를 의미합니다

See all articles