I'm working with an array containing data received from an api. Each object in the array has a createdOn field that is a date. I'm having a problem converting this dates to the format YYYYDDMMHHmmss since not all the dates are in the same format.

sample dates are as follow :

date1 = 20190425125221, date2 = Wed, 30 Jan 2019 08:57:17 GMT

I created another array that will contain all the converted dates. I tried using the angular date pipe to transform the dates to a unified format and then used momentjs to convert the dates to my desired format but i get "invalidDate".

like

constructor(private transformer: DatePipe) {}
   ....
const myNewArr = arr.map((val, i, arr) => {

const myDate = this.transformer.transform(val.createdOn, 'MMM/dd/yyyy');

const convertedDate=moment(myDate,'MMM/dd/yyyy').format('YYYYDDMMHHmmss');

return convertedDate;
});

...

i expect the the converted dates to resemble this date pattern 'YYYYDDMMHHmmss'.

1 Answers

0
Anthony Kong On Best Solutions

You need an if loop to differentiate different date formats. For example, the line const convertedDate=moment(myDate,'MMM/dd/yyyy').format('YYYYDDMMHHmmss'); can be rewritten as

let convertedDate;
if (isNaN(myDate)) {
 convertedDate = moment(myDate,'MMM/dd/yyyy').format('YYYYDDMMHHmmss');
} else {
convertedDate = myDate; // already in YYYYDDMMHHmmss format like date1
}