date.toISOString().slice(0, 19).replace('T', ' ')在IE浏览器中不能用,请改写成IE浏览器能用的样子
时间: 2024-01-17 16:05:39 浏览: 25
可以改写成以下形式:
```
function formatDate(date) {
var year = date.getUTCFullYear();
var month = date.getUTCMonth() + 1;
var day = date.getUTCDate();
var hour = date.getUTCHours();
var minute = date.getUTCMinutes();
var second = date.getUTCSeconds();
return year + '-' + pad(month) + '-' + pad(day) + ' ' + pad(hour) + ':' + pad(minute) + ':' + pad(second);
}
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
var date = new Date();
var isoDate = formatDate(date);
console.log(isoDate);
```
这个函数将日期格式化为ISO 8601格式的字符串,以便在IE浏览器中使用。
相关问题
我在js中这样写获取的时间是当地时间还是0时区时间 let now = new Date(); let today = new Date(); today.setHours(0); today.setMinutes(0); today.setSeconds(0); let formattedToday = today.toISOString().slice(0, 19).replace('T', ' '); let formattedNow = now.toISOString().slice(0, 19).replace('T', ' ')
这段代码获取的时间是当地时间,即使用了浏览器所在地的时区。`new Date()`方法返回的是当前的本地时间,而`toISOString()`方法将时间转换成了ISO 8601格式的字符串,其中包含了当前时区的信息。因此,这段代码获取的时间是当地时间,而不是0时区的时间。如果你想要获取0时区的时间,可以使用`Date.UTC()`方法,该方法会返回一个标准的UTC时间,而不是本地时间。例如,可以将以上代码修改为:
```javascript
let now = new Date(Date.UTC());
let today = new Date(Date.UTC());
today.setUTCHours(0);
today.setUTCMinutes(0);
today.setUTCSeconds(0);
let formattedToday = today.toISOString().slice(0, 19).replace('T', ' ');
let formattedNow = now.toISOString().slice(0, 19).replace('T', ' ');
```
这样获取的时间就是0时区的时间了。
优化new Date().toISOString().slice(0, 10)只要日期不要时间
您可以使用`Date.prototype.toDateString()`方法来仅获取日期部分,如下所示:
```javascript
var currentDate = new Date();
var formattedDate = currentDate.toDateString();
console.log(formattedDate); // 输出:"Mon Oct 18 2021"
```
这将返回一个字符串,格式为`"Day Month Date Year"`,其中`Month`是英文缩写。如果您需要使用特定的日期格式,请使用其他日期格式化库(如Moment.js)。