文章目录

前段时间做的一个集助活动,其中有一个倒计时,需要计算两个时间节点之间的差值,然后转化为时分秒,我用的是将两个时间节点传入new Date(),然后getTime()计算差值,代码大致如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 仅是两个时间点是同一天的简单换算
function timeFormat(newTimeStr, oldTimeStr){
var newTime = new Date(newTimeStr).getTime();
var oldTime = new Date(oldTimeStr).getTime();
var diffTime = newTime - oldTime;
if(diffTime < 0){
return "请确保参数顺序";
}
var hh = Math.floor(diffTime / 60 / 60 / 1000);
hh = hh < 10 ? "0" + hh : hh;
diffTime -= hh * 60 * 60 * 1000;
var mm = Math.floor(diffTime / 60 / 1000);
mm = mm < 10 ? "0" + mm : mm;
diffTime -= mm * 60 * 1000;
var ss = Math.floor(diffTime / 1000);
return hh + ":" + mm + ":" + ss;
}
timeFormat("2018-05-11 15:09:09", "2018-05-11 12:10:10");

上面代码在Google浏览器正常,在安卓手机里面也正常,但是在iphone内一直出问题,我在网上查了查,大致意思是Safari不支持”2018-05-11 15:10:10”这种时间格式的new Date()参数,所以我写了下面这个例子来试试:
可点击此处查看,或者是直接用手机扫描下面的二维码:二维码

例子代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ios端关于Date()格式的兼容</title>
</head>

<body>
<script>
alert("new Date('2018-05-11 12:00:00').getMonth() :" + new Date("2018-05-11 12:00:00").getMonth());
alert("new Date('2018/05/11 12:00:00').getMonth() :" + new Date("2018/05/11 12:00:00").getMonth());
var time = '2018-05-11 12:00:00';
var arr = time.split(/[- : \/]/);
var d = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
alert("new Date(" + arr[0] + "," + (arr[1] - 1) + "," + arr[2] + "," + arr[3] + "," + arr[4] + "," + arr[5] + ") : " + d.getMonth());
</script>
</body>

</html>

例子是为了试一下浏览器的new Date()对’2018-05-11 12:00:00’和’2018/05/11 12:00:00’时间格式的兼容性。

如果你用的是Safari,那么你应该会看到第一个的提示是:

new Date(‘2018-05-11 12:00:00’).getMonth() :NAN

说明其不兼容’2018-05-11 12:00:00’这种时间格式,但是我们为了兼容,所以我将上面的第一段代码更改为如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 仅是两个时间点是同一天的简单换算
function timeFormat(newTimeStr, oldTimeStr){
newTimeStr = newTimeStr.replace(/-/g, "/");
oldTimeStr = oldTimeStr.replace(/-/g, "/");
var newTime = new Date(newTimeStr).getTime();
var oldTime = new Date(oldTimeStr).getTime();
var diffTime = newTime - oldTime;
if(diffTime < 0){
return "请确保参数顺序";
}
var hh = Math.floor(diffTime / 60 / 60 / 1000);
hh = hh < 10 ? "0" + hh : hh;
diffTime -= hh * 60 * 60 * 1000;
var mm = Math.floor(diffTime / 60 / 1000);
mm = mm < 10 ? "0" + mm : mm;
diffTime -= mm * 60 * 1000;
var ss = Math.floor(diffTime / 1000);
ss = ss < 10 ? "0" + ss : ss;
return hh + ":" + mm + ":" + ss;
}
timeFormat("2018-05-11 15:09:09", "2018-05-11 12:10:10");

如此就兼容所有的浏览器了。关于Date的详细信息可查看:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date

文章目录