项目场景:
全省医疗单位会计核算数据标准接口记录。
json格式中的时间递归自动查找,JavaScript时间格式转换
问题描述
时间格式转换,一般时间都是带_date和_time的时间
把时间一个一个的找出来再替换浪费时间
接口太多太杂,时间参数部分一致,部分不同
如:创建时间:create_date
解决方案:
为解决这个问题,用js识别_date和_time的数据字段
由于可能包含在[time,{time},{{time}}] 这样的子串中,所以需要递归查询
示例代码:
function timeFormatStampAtArray(array) {
// 时间格式转换 gla_vou_head
if (array && Array.isArray(array)) {
array.forEach((obj) => {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
if ((key.includes('_date') || key.includes('_time')) && typeof value === 'string' && !isNaN(Date.parse(value))) {
obj[key] = timeFormatStamp(value);
console.log(`Variable ${key} contains a valid date: ${obj[key]}`);
} else if (typeof value === 'object') {
// 如果属性的值是对象,则递归调用 extractDateVariables
extractDateVariables(value);
}
}
}
});
} else {
console.error('不是一个有效的数组或对象');
}
}
时间格式转换:
原本格式:时间戳,即一串数字
更改为yyyyMMddhhmmss格式
function timeFormatStamp(time) {
var date = new Date(time);
var year = date.getFullYear();
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
var hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
var minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
return "" + year + month + day + hour + minute + second;
}