Skip to content

Commit

Permalink
fix(route): 修复观察者网风闻社区出现 Invalid Date 的错误 (DIYgod#7458)
Browse files Browse the repository at this point in the history
  • Loading branch information
lynzrand authored May 8, 2021
1 parent e4ad73e commit 27240d9
Showing 1 changed file with 39 additions and 5 deletions.
44 changes: 39 additions & 5 deletions lib/routes/guancha/personalpage.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,48 @@ module.exports = async (ctx) => {
});
const list = response.data.data.items;
const user_nick = list[0].user_nick;

/** Get time from relative time in HTML */
function getpass_at(e) {
// 修复数据返回缺少年份 但是 几个小时前的就不想写了 = =
if (e.length === 11) {
const now = new Date();
const minuteRelativeTime = /(\d+)\s*/;
const hourRelativeTime = /(\d+)\s*/;
const yesterdayRelativeTime = /\s*(\d+):(\d+)/;
const shortDate = /(\d+)-(\d+)\s*(\d+):(\d+)/;

// offset to ADD for transforming China time to UTC
const chinaToUtcOffset = -8 * 3600 * 1000;
// offset to ADD for transforming local time to UTC
const localToUtcOffset = new Date().getTimezoneOffset() * 60 * 1000;
// offset to ADD for transforming local time to china time
const localToChinaOffset = localToUtcOffset - chinaToUtcOffset;

let time;
if (e === '刚刚') {
time = new Date();
} else if (minuteRelativeTime.test(e)) {
const rel = minuteRelativeTime.exec(e);
time = new Date(Date.now() - parseInt(rel[1]) * 60 * 1000);
} else if (hourRelativeTime.test(e)) {
const rel = hourRelativeTime.exec(e);
time = new Date(Date.now() - parseInt(rel[1]) * 60 * 60 * 1000);
} else if (yesterdayRelativeTime.test(e)) {
const rel = yesterdayRelativeTime.exec(e);
// this time is China time data in local timezone
time = new Date(Date.now() - 86400 * 1000 + localToChinaOffset);
time.setHours(parseInt(rel[1]), parseInt(rel[2]), 0, 0);
// transform back to china timezone
time = new Date(time.getTime() - localToChinaOffset);
} else if (shortDate.test(e)) {
const rel = shortDate.exec(e);
const now = new Date(Date.now() + localToChinaOffset);
const year = now.getFullYear();
e = year + '-' + e;
// this time is China time data in local timezone
time = new Date(year, parseInt(rel[1]) - 1, parseInt(rel[2]), parseInt(rel[3]), parseInt(rel[4]));
// transform back to china timezone
time = new Date(time.getTime() - localToChinaOffset);
} else {
time = new Date(e);
}
const time = new Date(e).toLocaleString();
return time;
}
ctx.state.data = {
Expand Down

0 comments on commit 27240d9

Please sign in to comment.