From d4d0380432dc86fd9d59a5c410b8ca75a7813885 Mon Sep 17 00:00:00 2001 From: enagic Date: Sun, 23 Aug 2020 04:48:13 -0400 Subject: [PATCH] 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. --- .../shared-utils/src/getPermalink.ts | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/packages/@vuepress/shared-utils/src/getPermalink.ts b/packages/@vuepress/shared-utils/src/getPermalink.ts index ef6f026a5e..7207fff873 100644 --- a/packages/@vuepress/shared-utils/src/getPermalink.ts +++ b/packages/@vuepress/shared-utils/src/getPermalink.ts @@ -12,6 +12,38 @@ interface PermalinkOption { function removeLeadingSlash (path: string) { return path.replace(/^\//, '') } + +function toUtcTime (date: string | Date): number { + let year = 1970 + let month = 0 + let day = 1 + + if (typeof date === 'string') { + const [ + yearStr, + monthStr, + dayStr + ] = date.split('-') + + year = parseInt(yearStr, 10) + month = parseInt(monthStr, 10) - 1 + day = parseInt(dayStr, 10) + } else if (date instanceof Date) { + // If `date` is an instance of Date, + // it's because it was parsed from the frontmatter + // by js-yaml, which always assumes UTC + return date.getTime() + } + + return Date.UTC(year, month, day) +} + +function addTzOffset (utc: number): Date { + const utcDate = new Date(utc) + + return new Date(utc + utcDate.getTimezoneOffset() * 60 * 1000) +} + // e.g. // filename: docs/_posts/evan you.md // content: # yyx 990803 @@ -33,7 +65,7 @@ export = function getPermalink ({ } slug = encodeURI(slug) - const d = new Date(date) + const d = addTzOffset(toUtcTime(date)) const year = d.getFullYear() const iMonth = d.getMonth() + 1 const iDay = d.getDate()