JavaScript 时间戳判断及格式化 - 前端JS代码实现
你可以使用JavaScript的'Date'对象来判断是否为时间戳,并将时间戳转换为正常的时间格式。以下是代码示例:
function isTimestamp(timestamp) {
// 判断是否为数字类型且大于0,可根据实际情况进行调整
if (typeof timestamp === 'number' && timestamp > 0) {
return true;
} else {
return false;
}
}
function formatTimestamp(timestamp) {
const date = new Date(timestamp);
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
const hour = ('0' + date.getHours()).slice(-2);
const minute = ('0' + date.getMinutes()).slice(-2);
const second = ('0' + date.getSeconds()).slice(-2);
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}
// 示例使用
const timestamp1 = 1632816000000; // 时间戳
const timestamp2 = 1632816000; // 非时间戳
if (isTimestamp(timestamp1)) {
const formattedTime1 = formatTimestamp(timestamp1);
console.log(formattedTime1); // 输出:2021-09-28 00:00:00
} else {
console.log(timestamp1); // 非时间戳,不做处理
}
if (isTimestamp(timestamp2)) {
const formattedTime2 = formatTimestamp(timestamp2);
console.log(formattedTime2); // 非时间戳,不做处理
} else {
console.log(timestamp2);
}
在代码中,'isTimestamp'函数用于判断是否为时间戳,它检查传入的值是否为数字类型且大于0,你可以根据实际需求进行调整。'formatTimestamp'函数用于将时间戳转换为正常的时间格式,它使用'Date'对象的相关方法获取年、月、日、时、分、秒,并进行格式化拼接。最后,根据判断结果进行相应的处理。
在示例中,'timestamp1'是一个时间戳,它会被转换为正常的时间格式并输出。而'timestamp2'不是一个时间戳,所以不会进行处理,直接输出原始值。你可以根据实际情况,调用相应的函数来判断和处理时间戳。
原文地址: https://www.cveoy.top/t/topic/bOPm 著作权归作者所有。请勿转载和采集!