Вы можете проанализировать строку как дату. Если строка является допустимой датой, она возвращает число, представляющее миллисекунды, прошедшие с 1 января 1970 года, 00:00:00 UT C, в противном случае возвращается NaN
.
/**
* Check if the string is a valid date string or not.
* For that we check if the given string is really a string, not a number.
* Because a number is parsed as a date by Date.parse()
*/
function isDate(str) {
let date = Date.parse(str);
return (typeof str === 'object' && str instanceof Date) || (typeof str === 'string' && isNaN(+str) && !isNaN(date));
}
/**
* These are some examples
*
*/
let dateString = "Thu Mar 26 2020 05:30:00 GMT+0530 (India Standard Time)";
let nonDateString = "Hello world";
let object = {
employeeid: "4",
id: 276,
birthdate: "Thu Mar 26 2020 05:30:00 GMT+0530 (India Standard Time)",
status: "pending"
};
console.log('Date string: ', isDate(dateString));
console.log('Non date string:', isDate(nonDateString));
// Check a date object rather than a date string. It works for it as well.
console.log('Date object:', isDate(new Date()));
if (isDate(object.birthdate)) {
console.log(`${object.birthdate}: is a date string.`);
} else {
console.log(`${object.birthdate}: is not a date string.`);
}
.as-console-wrapper{min-height: 100%!important; top: 0;}
Обновление
Для вашего измененного запроса я обновляю этот ответ. Поскольку вам нужны все значения объекта со строками даты, для этого я создаю новый объект со всеми датами и преобразую строки даты в строку UT C.
/**
* Check if a string is a date or not.
*/
function isDate(str) {
let date = Date.parse(str);
return (typeof str === 'object' && str instanceof Date) || (typeof str === 'string' && isNaN(+str) && !isNaN(date));
}
const obj = {
employeeid: "4",
id: 276,
birthdate: "Thu Mar 26 2020 05:30:00 GMT+0530 (India Standard Time)",
status: "pending",
join: Date('2020-01-12')
};
/**
* This will makes a new object with the date types
* and also convert the date into a UTC string.
*/
const dates = Object.entries(obj).reduce((a, [key, value]) => {
return isDate(value) ? {...a, [key]: new Date(value).toUTCString()} : a;
}, {});
console.log(dates);
.as-console-wrapper {min-height: 100%!important; top: 0;}