关于爬取抖音遇到时间格式不统一解决
问题
今天在做抖音时候需要获取时间,时间格式参差不一:
解决
function formatDateString(input) {
let currentDate = new Date(); // 当前日期
let year = "" + currentDate.getFullYear(); // 年份
let month = "" + (currentDate.getMonth() + 1); // 月份(注意:月份从0开始,所以要加1)
let day = "" + currentDate.getDate(); // 日期
if (input.includes("周前")) {
// 字符串中包含周的情况
let weekAgo = parseInt(input); // 提取周数
let targetDate = new Date(year, month - 1, day - weekAgo * 7); // 计算目标日期
let targetMonth = "" + (targetDate.getMonth() + 1);
let targetDay = "" + targetDate.getDate();
return targetMonth.padStart(2, "0") + "月" + targetDay.padStart(2, "0") + "日";
} else if (input.includes("天前")) {
// 字符串中包含天前的情况
let daysAgo = parseInt(input);
let targetDate = new Date(year, month - 1, day - daysAgo); // 计算目标日期
let targetMonth = "" + (targetDate.getMonth() + 1);
let targetDay = "" + targetDate.getDate();
return targetMonth.padStart(2, "0") + "月" + targetDay.padStart(2, "0") + "日";
} else if (input.includes("小时前")) {
// 字符串中包含小时前的情况
let hoursAgo = parseInt(input);
let targetDate = new Date(year, month - 1, day, 0, 0, 0); // 当天的凌晨
targetDate.setHours(targetDate.getHours() - hoursAgo); // 计算目标日期
let targetMonth = "" + (targetDate.getMonth() + 1);
let targetDay = "" + targetDate.getDate();
return targetMonth.padStart(2, "0") + "月" + targetDay.padStart(2, "0") + "日";
} else if (input.includes("分钟前")) {
let minutesAgo = parseInt(input);
let targetDate = new Date(year, month - 1, day, 0, 0, 0); // 当天的凌晨
targetDate.setMinutes(targetDate.getMinutes() - minutesAgo); // 计算目标日期
let targetMonth = "" + (targetDate.getMonth() + 1);
let targetDay = "" + targetDate.getDate();
return targetMonth.padStart(2, "0") + "月" + targetDay.padStart(2, "0") + "日";
} else {
return input;
}
}
console.log(formatDateString("2天前"))
console.log(formatDateString("1周前"))
console.log(formatDateString("3分钟前"))
console.log(formatDateString("12小时前"))
console.log(formatDateString("21小时前"))
效果
阅读剩余
版权声明:
作者:admin
链接:https://www.denceun.com/archives/364
文章版权归作者所有,未经允许请勿转载。
THE END