0

I have a variable that's returning the following content:

{
    "id":1,
    "refnumber":3,
    "active":false,
    "date":"2017-09-14T23:00:00.000Z",
    "addons":0,
    "age":0
}

If you look at the data field I need a way of changing the data on that field to yyyy-mm-dd.

In other words .. if we take this example as a reference I would need the data field value:

This:

2017-09-14T23:00:00.000Z

To be changed to this:

2017-09-14

How can I do this?

4 Answers 4

1

You should just be able to slice away the trailing characters.

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

This works because your data format is in a predictable form where the month and day have a 0 padding.

Sign up to request clarification or add additional context in comments.

Comments

0

I recommend a library called momentjs for all your javascript date manipulation needs.

https://momentjs.com/

With it, you can do what you want easily: moment(data.date).format('YYYY-MM-DD')

1 Comment

no need for moment, if you have an ISO 8601 string and need just to make is shorter.
0

Note that your JSON is invalid because the date string is not properly quoted, but assuming it's corrected and that your JSON object is named myObject, the following would work:

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());

Comments

0

Well you could convert the string to date and then format it Here is an example

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.