侧边栏壁纸
博主头像
落叶人生博主等级

走进秋风,寻找秋天的落叶

  • 累计撰写 130562 篇文章
  • 累计创建 28 个标签
  • 累计收到 9 条评论
标签搜索

目 录CONTENT

文章目录

iOS下Date.parse失效的解决方法

2024-05-12 星期日 / 0 评论 / 0 点赞 / 93 阅读 / 4460 字

使用标准格式的字符串‘2015-10-17 15:37:28’作为Date.parse()的参数,将字符串转换为日期对象,结果在iOS下执行失败,在网上查了一下,都说是Safari不支持这个特性。 因

使用标准格式的字符串‘2015-10-17 15:37:28’作为Date.parse()的参数,将字符串转换为日期对象,结果在iOS下执行失败,在网上查了一下,都说是Safari不支持这个特性。

因此在Safari下转换字符串到日期对象,需要自己解析字符串并设置到日期对象里,封装了一个对象如下:

Date.prototype.setISO8601 = function(dString){
    var regexp = /(/d/d/d/d)(-)?(/d/d)(-)?(/d/d)(T)?(/d/d)(:)?(/d/d)(:)?(/d/d)(/./d+)?(Z|([+-])(/d/d)(:)?(/d/d))/;

    if (dString.toString().match(new RegExp(regexp))) {
        var d = dString.match(new RegExp(regexp));
        var offset = 0;

        this.setUTCDate(1);
        this.setUTCFullYear(parseInt(d[1],10));
        this.setUTCMonth(parseInt(d[3],10) - 1);
        this.setUTCDate(parseInt(d[5],10));
        this.setUTCHours(parseInt(d[7],10));
        this.setUTCMinutes(parseInt(d[9],10));
        this.setUTCSeconds(parseInt(d[11],10));
        if (d[12])
            this.setUTCMilliseconds(parseFloat(d[12]) * 1000);
        else
            this
.setUTCMilliseconds(0);
        if (d[13] != 'Z') {
            offset = (d[15] * 60) + parseInt(d[17],10);
            offset *= ((d[14] == '-') ? -1 : 1);
            this.setTime(this.getTime() - offset * 60 * 1000);
        }
    }
    else {
        //日期格式:yyyy-mm-dd hh:mm:ss
        regexp = /(/d/d/d/d)(-)?(/d/d)(-)?(/d/d) (/d/d)(:)?(/d/d)(:)?(/d/d)/;
        d = dString.match(new RegExp(regexp));
        if (d) {
            this.setFullYear(parseInt(d[1], 10));
            this.setMonth(parseInt(d[3], 10) - 1);
            this.setDate(parseInt(d[5], 10));
            this.setHours(parseInt(d[6], 10));
            this.setMinutes(parseInt(d[8], 10));
            this.setSeconds(parseInt(d[10], 10));
            this.setMilliseconds(0);
        } else {
            this.setTime(Date.parse(dString));
        }
    }
    return this;
};

 

调用:

var sendTime = new Date().setISO8601(‘2015-10-17 15:42:38’);

 

广告 广告

评论区