Javascript更改某些数据中的数据

Javascript更改某些数据中的数据,javascript,Javascript,我有一个返回以下内容的变量: { "id":1, "refnumber":3, "active":false, "date":"2017-09-14T23:00:00.000Z", "addons":0, "age":0 } 如果您查看数据字段,我需要一种将该字段上的数据更改为yyyy-mm-dd的方法 换句话说。。如果我们将此示例作为参考,我需要数据字段值: 这: 改为: 2017-09-14 我怎样才能做到这一点?您应该能够切掉尾随字符 d

我有一个返回以下内容的变量:

{
    "id":1,
    "refnumber":3,
    "active":false,
    "date":"2017-09-14T23:00:00.000Z",
    "addons":0,
    "age":0
}
如果您查看数据字段,我需要一种将该字段上的数据更改为yyyy-mm-dd的方法

换句话说。。如果我们将此示例作为参考,我需要数据字段值:

这:

改为:

2017-09-14

我怎样才能做到这一点?

您应该能够切掉尾随字符

data.date = data.date.slice(0, 10);

这是因为您的数据格式是一种可预测的格式,其中月份和日期都有一个
0
填充。

我推荐一个名为momentjs的库来满足您所有的javascript日期操作需求


有了它,您可以轻松地做您想做的事情:
moment(data.date).format('YYYY-MM-DD')
请注意,您的JSON是无效的,因为
date
字符串没有正确引用,但假设它已更正,并且您的JSON对象名为
myObject
,以下操作将有效:

var date = new Date(myObject.date); //your string will become a date object

//now operate on that date object by extracting the year, month,
//and day into a string
console.log(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate());

您可以将字符串转换为日期,然后格式化它 这里有一个例子

function formate(date) {
if (typeof date == "string")
    date = new Date(date);
  var day = (date.getDate() <= 9 ? "0" + date.getDate() : 
 date.getDate());
 var month = (date.getMonth() + 1 <= 9 ? "0" + 
(date.getMonth() + 1) : (date.getMonth() + 1));
var dateString = day + "-" + month + "-" + 
date.getFullYear() + " " + date.getHours() + ":" + 
date.getMinutes();

return dateString;
}
函数格式(日期){
如果(日期类型=“字符串”)
日期=新日期(日期);

var day=(date.getDate()不需要片刻,若您有一个字符串,只需使其变短即可。
function formate(date) {
if (typeof date == "string")
    date = new Date(date);
  var day = (date.getDate() <= 9 ? "0" + date.getDate() : 
 date.getDate());
 var month = (date.getMonth() + 1 <= 9 ? "0" + 
(date.getMonth() + 1) : (date.getMonth() + 1));
var dateString = day + "-" + month + "-" + 
date.getFullYear() + " " + date.getHours() + ":" + 
date.getMinutes();

return dateString;
}