JavaScript: Array Of Numbers To Date-time String Format
I have an array of number var year = [1999,2000,2001,2002,2003]; and I need to convert to date-time formar var yearConvert =['1999-00-00','2000-00-00','2001-00-00','20002-00-00','
Solution 1:
You can use map and concat -00-00
on each element
var year = [1999,2000,2001,2002,2003];
let op = year.map(e => e+'-00-00')
console.log(op)
Solution 2:
You could use a IIFE generator function with the spread syntax and yield
each value into an array like so:
const year = [1999,2000,2001,2002,2003],
yearConvert = [...(function*(a){
for(y of a) yield `${y}-00-00`;
})(year)];
console.log(yearConvert);
Solution 3:
You can use Array#map
to do it. But the returned array will have the values as string not as Date
object.
const year = [1999,2000,2001,2002,2003];
const dateString = year.map((ele) => `${ele}-00-00`);
console.log(dateString);
//Convert this array to Date Objects using Date constructor Date(year, monthIndex, day) month starts from '0'
const date = dateString.map((str) => {
const data = str.split('-');
return new Date(data[0], data[1], data[2]+1);
});
console.log(date)
//To verify parse to date strings
const dateParsed = date.map((date) => date.toDateString());
console.log(dateParsed);
Post a Comment for "JavaScript: Array Of Numbers To Date-time String Format"