Skip to content

Commit d4d0380

Browse files
authoredAug 23, 2020
fix($shared-utils): fix date parse logic for permalinks (#2181)
This addresses the way the date is parsed, which, when it's a string is causing the input for the Date constructor to assume the date to be in ISO 8601 format (UTC), and when it's a Date, is always UTC.
1 parent dd26c7c commit d4d0380

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed
 

‎packages/@vuepress/shared-utils/src/getPermalink.ts

+33-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,38 @@ interface PermalinkOption {
1212
function removeLeadingSlash (path: string) {
1313
return path.replace(/^\//, '')
1414
}
15+
16+
function toUtcTime (date: string | Date): number {
17+
let year = 1970
18+
let month = 0
19+
let day = 1
20+
21+
if (typeof date === 'string') {
22+
const [
23+
yearStr,
24+
monthStr,
25+
dayStr
26+
] = date.split('-')
27+
28+
year = parseInt(yearStr, 10)
29+
month = parseInt(monthStr, 10) - 1
30+
day = parseInt(dayStr, 10)
31+
} else if (date instanceof Date) {
32+
// If `date` is an instance of Date,
33+
// it's because it was parsed from the frontmatter
34+
// by js-yaml, which always assumes UTC
35+
return date.getTime()
36+
}
37+
38+
return Date.UTC(year, month, day)
39+
}
40+
41+
function addTzOffset (utc: number): Date {
42+
const utcDate = new Date(utc)
43+
44+
return new Date(utc + utcDate.getTimezoneOffset() * 60 * 1000)
45+
}
46+
1547
// e.g.
1648
// filename: docs/_posts/evan you.md
1749
// content: # yyx 990803
@@ -33,7 +65,7 @@ export = function getPermalink ({
3365
}
3466
slug = encodeURI(slug)
3567

36-
const d = new Date(date)
68+
const d = addTzOffset(toUtcTime(date))
3769
const year = d.getFullYear()
3870
const iMonth = d.getMonth() + 1
3971
const iDay = d.getDate()

0 commit comments

Comments
 (0)
Please sign in to comment.