fix: parseRelativeDate in correct timezone

This commit is contained in:
Ou 2024-10-23 03:10:51 +08:00
parent 2edfb06a61
commit 4badad88e1
2 changed files with 8 additions and 5 deletions

View File

@ -15,13 +15,14 @@ export default defineSource(async () => {
const info = $(el).find(".time > span:nth-child(1)").text()
// 第三个 p
const relatieveTime = $(el).find(".time > span:nth-child(3)").text()
console.log(relatieveTime)
if (url && title && relatieveTime) {
news.push({
url: baseURL + url,
title,
id: url,
extra: {
date: parseRelativeDate(relatieveTime),
date: parseRelativeDate(relatieveTime, "Asia/Shanghai"),
info,
},
})

View File

@ -140,7 +140,7 @@ function toDurations(matches: string[]) {
export const parseDate = (date: string | number, ...options: any) => dayjs(date, ...options).toDate()
export function parseRelativeDate(date: string, timezone: string = "Asia/Shanghai") {
export function parseRelativeDate(date: string, timezone: string = "UTC") {
if (date === "刚刚") return new Date()
// 预处理日期字符串 date
@ -149,6 +149,7 @@ export function parseRelativeDate(date: string, timezone: string = "Asia/Shangha
// 将 `\d+年\d+月...\d+秒前` 分割成 `['\d+年', ..., '\d+秒前']`
const matches = theDate.match(/\D*\d+(?![:\-/]|(a|p)m)\D+/g)
const offset = dayjs.duration({ hours: (dayjs().tz(timezone).utcOffset() - dayjs().utcOffset()) / 60 })
if (matches) {
// 获得最后的时间单元,如 `\d+秒前`
@ -192,12 +193,13 @@ export function parseRelativeDate(date: string, timezone: string = "Asia/Shangha
// 取特殊词对应日零时为起点,加上相应的时间长度
return w.startAt
.set("hour", (dayjs().tz(timezone).utcOffset() - dayjs().utcOffset() / 60))
return dayjs.tz(w.startAt
.set("hour", 0)
.set("minute", 0)
.set("second", 0)
.set("millisecond", 0)
.add(dayjs.duration(toDurations(matches)))
.add(offset), timezone)
.toDate()
}
}
@ -211,7 +213,7 @@ export function parseRelativeDate(date: string, timezone: string = "Asia/Shangha
if (wordMatches) {
// The default parser of dayjs() can parse '8:00 pm' but not '8:00pm'
// so we need to insert a space in between
return dayjs.tz(`${w.startAt.format("YYYY-MM-DD")} ${/a|pm$/.test(wordMatches[1]) ? wordMatches[1].replace(/a|pm/, " $&") : wordMatches[1]}`, timezone).toDate()
return dayjs.tz(`${w.startAt.add(offset).format("YYYY-MM-DD")} ${/a|pm$/.test(wordMatches[1]) ? wordMatches[1].replace(/a|pm/, " $&") : wordMatches[1]}`, timezone).toDate()
}
}
}