javascript中new Date()构造函数在fireFox和ie不兼容的问题

本文详细介绍了在JavaScript中遇到使用newDate(str)创建时间对象时,不同浏览器(如Firefox和IE)之间的兼容性问题,并提供了三种有效的解决方案。包括使用Date.parse()、Date.UTC()以及直接使用Date()构造函数的方法,以确保时间对象在多种浏览器环境下的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//js中使用new Date(str)创建时间对象不兼容firefox和ie的问题
//比如2016-01-29格式的时间字符串通过new Date()将不能得到正确的时间对象
//处理方式如下:

            var endDate = '2016-01-29';

            //方式一:Date.parse()
            //字符串格式转换:2016-01-29转换为2016/01/29,来兼容firefox
            endDate = endDate.replace("-", "/").replace("-", "/");//endDate.replace(/-/g,'/');
            //将时间字符串先获取毫秒
            var times = Date.parse(endDate);////返回毫秒
            //转换为时间类型
            endDate = new Date(times);
            console.log(endDate);

            //方式二,Date.UTC()
            //字符串格式分割为年、月、日、时、分、秒的数组,来兼容firefox
            var DateTime = startDate.split(" ");//日期和时间分割
            var date = DateTime[0].split("-");

            //转换毫秒
            var times = Date.UTC(date[0],date[1],date[2]);//返回毫秒
            //转换为时间类型
            endDate = new Date(times);
            console.log(endDate);

            //最后:方式三
            //可以不使用Date.parse('strDateTime')或Date.UTC(年,月,日,时,分,秒)(年、月是必需的),直接将参数给Date()构造函数
            //Date()构造函数内部会模仿Date.parse('strDateTime')或Date.UTC(年,月,日,时,分,秒)进行转换

            var times = new Date(endDate);//模仿Date.parse('strDateTime')
            var times = new Date(date[0],date[1],date[2]);//模仿Date.UTC(年,月,日,时,分,秒)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值