feat: support timezone offset argument for date filter, #553

This commit is contained in:
Jun Yang
2022-11-27 13:46:51 +08:00
parent cd918ccb85
commit 7a714855df
2 changed files with 9 additions and 4 deletions
+6 -4
View File
@@ -4,11 +4,11 @@ import { toValue, stringify, isString, isNumber } from '../../util/underscore'
import { FilterImpl } from '../../template/filter/filter-impl' import { FilterImpl } from '../../template/filter/filter-impl'
import { TimezoneDate } from '../../util/timezone-date' import { TimezoneDate } from '../../util/timezone-date'
export function date (this: FilterImpl, v: string | Date, arg: string) { export function date (this: FilterImpl, v: string | Date, format: string, timeZoneOffset?: number) {
const opts = this.context.opts const opts = this.context.opts
let date: LiquidDate let date: LiquidDate
v = toValue(v) v = toValue(v)
arg = stringify(arg) format = stringify(format)
if (v === 'now' || v === 'today') { if (v === 'now' || v === 'today') {
date = new Date() date = new Date()
} else if (isNumber(v)) { } else if (isNumber(v)) {
@@ -25,10 +25,12 @@ export function date (this: FilterImpl, v: string | Date, arg: string) {
date = v date = v
} }
if (!isValidDate(date)) return v if (!isValidDate(date)) return v
if (opts.hasOwnProperty('timezoneOffset')) { if (timeZoneOffset !== undefined) {
date = new TimezoneDate(date, timeZoneOffset)
} else if (opts.timezoneOffset !== undefined) {
date = new TimezoneDate(date, opts.timezoneOffset!) date = new TimezoneDate(date, opts.timezoneOffset!)
} }
return strftime(date, arg) return strftime(date, format)
} }
function isValidDate (date: any): date is Date { function isValidDate (date: any): date is Date {
+3
View File
@@ -61,6 +61,9 @@ describe('filters/date', function () {
it('should offset UTC date literal', function () { it('should offset UTC date literal', function () {
return test('{{ "1990-12-31T23:00:00Z" | date: "%Y-%m-%dT%H:%M:%S"}}', '1990-12-31T17:00:00', undefined, opts) return test('{{ "1990-12-31T23:00:00Z" | date: "%Y-%m-%dT%H:%M:%S"}}', '1990-12-31T17:00:00', undefined, opts)
}) })
it('should support timezone offset argument', function () {
return test('{{ "1990-12-31T23:00:00Z" | date: "%Y-%m-%dT%H:%M:%S", 360}}', '1990-12-31T17:00:00')
})
it('should offset date literal with timezone 00:00 specified', function () { it('should offset date literal with timezone 00:00 specified', function () {
return test('{{ "1990-12-31T23:00:00+00:00" | date: "%Y-%m-%dT%H:%M:%S"}}', '1990-12-31T17:00:00', undefined, opts) return test('{{ "1990-12-31T23:00:00+00:00" | date: "%Y-%m-%dT%H:%M:%S"}}', '1990-12-31T17:00:00', undefined, opts)
}) })