Skip to content

Commit

Permalink
Fix format handling of quoted text next to a time zone token, closed #…
Browse files Browse the repository at this point in the history
  • Loading branch information
marnusw committed Sep 13, 2021
1 parent d76f43a commit 19a6a23
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
19 changes: 16 additions & 3 deletions src/format/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -321,10 +321,23 @@ export default function format(dirtyDate, dirtyFormatStr, dirtyOptions) {
var matches = formatStr.match(tzFormattingTokensRegExp)
if (matches) {
var date = toDate(dirtyDate, options)
// Work through each match and replace the tz token in the format string with the quoted
// formatted time zone so the remaining tokens can be filled in by date-fns#format.
formatStr = matches.reduce(function (result, token) {
return token[0] === "'"
? result
: result.replace(token, "'" + formatters[token[0]](date, token, null, options) + "'")
if (token[0] === "'") {
return result // This is a quoted portion, matched only to ensure we don't match inside it
}
var pos = result.indexOf(token)
var precededByQuotedSection = result[pos - 1] === "'"
var replaced = result.replace(
token,
"'" + formatters[token[0]](date, token, null, options) + "'"
)
// If the replacement results in two adjoining quoted strings, the back to back quotes
// are removed so it doesn't look like an escaped quote.
return precededByQuotedSection
? replaced.substring(0, pos - 1) + replaced.substring(pos + 1)
: replaced
}, formatStr)
}

Expand Down
8 changes: 8 additions & 0 deletions src/format/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import assert from 'power-assert'
import format from '.'
import enGB from 'date-fns/locale/en-GB'
import utcToZonedTime from '../utcToZonedTime'

describe('format', function () {
var date = new Date(1986, 3 /* Apr */, 4, 10, 32, 55, 123)
Expand Down Expand Up @@ -667,6 +668,13 @@ describe('format', function () {
})
assert(result === dateAndTimeZoneAmericaNY)
})

it('handles quoted text next to a time zone token', function () {
var timeZone = 'Europe/Paris'
var result = format(utcToZonedTime(date, timeZone), "dd.MM.yyyy HH:mm 'UTC'xxx", { timeZone })

assert(result === '04.04.1986 11:32 UTC+02:00')
})
})

describe('timestamp', function () {
Expand Down

0 comments on commit 19a6a23

Please sign in to comment.