0

I have array with this timestamps,

var labels = ["2018-12-01T00:00:00.000Z", 
              "2018-12-02T00:00:00.000Z",
              "2018-12-09T00:00:00.000Z", 
              "2018-12-09T00:00:00.000Z",
              "2018-12-18T00:00:00.000Z" 
             ]

what is the best way to have array in format 2018-12-01. I need to have date for graph

1

4 Answers 4

1

You should use Array.prototype.map(), and create a new array with the characters you don't want sliced off the end:

var labels = ["2018-12-01T00:00:00.000Z", 
    "2018-12-02T00:00:00.000Z",
    "2018-12-09T00:00:00.000Z", 
    "2018-12-09T00:00:00.000Z",
    "2018-12-18T00:00:00.000Z" 
];

var truncated = labels.map(str => str.slice(0, -14));
console.log(truncated);

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

Comments

0

Have you considered using moment?

function updateTimeFormat(arr) {
  return arr.map(x => {
    return moment(x).format('YYYY-MM-DD');
  });
}

Comments

0

You can use the built-in Date, as so:

labels.map(label => {
    const date = new Date(label);
    return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
}

Comments

0

you can achieve what you want by using Array.prototype.map

var labels = ["2018-12-01T00:00:00.000Z", 
              "2018-12-02T00:00:00.000Z",
              "2018-12-09T00:00:00.000Z", 
              "2018-12-09T00:00:00.000Z",
              "2018-12-18T00:00:00.000Z" 
             ];

const newDates = labels.map( label => {
    const newd = new Date(label);
    const fullYear = newd.getFullYear();
    const month = (newd.getMonth() + 1 ).toString();
    const date = (newd.getDate()).toString();
    return `${fullYear}-${month.length > 1 ? month : month.replace(/^/,0)}-${date.length > 1 ? date : date.replace(/^/,0)}`;
});

console.log(newDates);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.