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()