If you are using any framework then use Datapipe in that framework.
Example: Datepipe-Angular
If you are not using any framework then use the date format utility function like:
df = (function(d) {
d = new Date(d);
return `${d.getFullYear()}-${(d.getMonth()+1).toString().replace(/^[0-9]$/g, '0$&')}-${(d.getDate()).toString().replace(/^[0-9]$/g, '0$&')} - ${(d.getHours()).toString().replace(/^[0-9]$/g, '0$&')}:${(d.getMinutes()).toString().replace(/^[0-9]$/g, '0$&')}:${(d.getSeconds()).toString().replace(/^[0-9]$/g, '0$&')}`;
});
console.log(df(new Date().toUTCString()));
Output:
'2022-07-22 - 14:41:36'
Explanation:
This is the objective to get data from the Date object.
d = new Date(d);
obj = {
date: d.getDate(),
month: d.getMonth(),
year: d.getFullYear(),
hour: d.getHours(),
minute: d.getMinutes(),
second: d.getSeconds()
}
I am using regular expression str.replace(/^[0-9]$/g, '0$&')
or str.replace(/^[0-9]{1}$/g, '0$&')
to add an addition zero if data is a single digit.
Like:
'0'.replace(/^[0-9]$/g, '0$&') // '00'
'8'.replace(/^[0-9]$/g, '0$&') // '08'
'12'.replace(/^[0-9]$/g, '0$&') //'12'