Skip to content

Commit

Permalink
fix($shared-utils): fix date parse logic for permalinks (#2181)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
enagic committed Aug 23, 2020
1 parent dd26c7c commit d4d0380
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion packages/@vuepress/shared-utils/src/getPermalink.ts
Expand Up @@ -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
Expand All @@ -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()
Expand Down

0 comments on commit d4d0380

Please sign in to comment.