kjx6gg
Last Updated: February 25, 2016
·
404
· richardgong1987
Psb  1

Compatibility Date type in Safari browser ,chrome,ie, ff

you know,in Safari browser we can't create a Date type like " new Date('2014-05-15')",if you not, that will be error;

so, we must custom a function to Compatibility it:

                    function parse(str) {
                            if (typeof str === 'undefined') {
                                return new Date();
                            }
                            if (typeof str === 'string') {
                                str = str || '';
                                var regtime = /^(\d{4})\-?(\d{1,2})\-?(\d{1,2})/i;
                                if (str.match(regtime)) {
                                    str = str.replace(regtime, "$2/$3/$1");
                                }
                                return new Date(str);
                            } else if (typeof str === 'number') {
                                return new Date(str);
                            } else {
                                return new Date();
                            }
                        }
                        console.log(parse('2015-12-13'));//Sun Dec 13 2015 00:00:00 GMT+0800


skill:

    var regtime = /^(\d{4})\-?(\d{1,2})\-?(\d{1,2})/i;
    str = '2015-12-16 10:15:15';
    console.log(str.match(regtime));
    console.log(RegExp.$1, RegExp.$2, RegExp.$3);
    console.log(str.replace(regtime, "$2/$3/$1"));
    // ["2015-12-16", "2015", "12", "16", index: 0, input: "2015-12-16 10:15:15"] test.js:17
    // 2015 12 16 test.js:18
    // 12/16/2015 10:15:15             

you know, in RegExp object there have "$" property that's used store "()" parenthesis mathed data;

$1 - $9; $1 is match first pattern;

when you use 'replace()' to replace some RegRxp data, like "console.log(str.replace(regtime, "$2/$3/$1"));" cos, you just direction use S1 to replace you wanna replace data, not the 'RegExp.$2', cos there are same context;

Say Thanks
Respond