Split date and time from api response

Viewed 318

I am getting an array of response from an api. Below is the response array.

[{createdBy:"user1",updatedDttm:
"2022-01-20T07:31:35.544Z"},
createdBy:"user2", updatedDttm:
"2022-02-20T09:31:37.544Z"}]

From the above response I want to split "updatedDttm" (date and time) for each user and save it to the same array as "date", " time" like below.

[{createdBy:"user1",date:
"2022-01-20", time:"07:31:35"},
createdBy:"user2", date:
"2022-02-20", time: "09:31:37"}]

I am using Angular.js.

2 Answers

Please find below a possible solution.

const response = [{createdBy:"user1",updatedDttm:'2022-01-20T07:31:35.544Z'},
{createdBy:"user2", updatedDttm: '2022-02-20T09:31:37.544Z'}].map(x => ({
 createdBy: x.createdBy,
 date: new Date(x.updatedDttm).toLocaleDateString(),
 time: new Date(x.updatedDttm).toLocaleTimeString(),
}));

console.log(response);

For what it's worth, not the most elegant solution, but if the data in your object is consistent you can try:

const a = [
    {
        "createdBy": "user1",
        "updatedDttm": "2022-01-20T07:31:35.544Z"
    },
    {
        "createdBy": "user2",
        "updatedDttm": "2022-02-20T09:31:37.544Z"
    }
];

const response = a.map(x => ({
 createdBy: x.createdBy,
 date: x['updatedDttm'].split('Z')[0].split('T')[0],
 time: x['updatedDttm'].split('Z')[0].split('T')[1].split('.')[0],
}));

console.log(response);

More elegant solutions are possible with momentjs and/or lodash;

Related