1
0
Fork 0
mirror of synced 2024-06-14 08:24:48 +12:00

Updating date helper to allow timezone capabilites.

This commit is contained in:
mike12345567 2021-06-09 11:44:24 +01:00
parent ae87ca1718
commit 3ffd340450
2 changed files with 31 additions and 2 deletions

View file

@ -3,6 +3,7 @@ dayjs.extend(require("dayjs/plugin/duration"))
dayjs.extend(require("dayjs/plugin/advancedFormat"))
dayjs.extend(require("dayjs/plugin/relativeTime"))
dayjs.extend(require("dayjs/plugin/utc"))
dayjs.extend(require("dayjs/plugin/timezone"))
/**
* This file was largely taken from the helper-date package - we did this for two reasons:
@ -72,7 +73,8 @@ function setLocale(str, pattern, options) {
// if options is null then it'll get updated here
const config = initialConfig(str, pattern, options)
const defaults = { lang: "en", date: new Date(config.str) }
const opts = getContext(this, defaults, config.options)
// for now don't allow this to be configurable, don't pass in options
const opts = getContext(this, defaults, {})
// set the language to use
dayjs.locale(opts.lang || opts.language)
@ -89,7 +91,15 @@ module.exports.date = (str, pattern, options) => {
setLocale(config.str, config.pattern, config.options)
const date = dayjs(new Date(config.str)).utc()
let date = dayjs(new Date(config.str))
if (typeof config.options === "string") {
date =
config.options.toLowerCase() === "utc"
? date.utc()
: date.tz(config.options)
} else {
date = date.tz(dayjs.tz.guess())
}
if (config.pattern === "") {
return date.toISOString()
}

View file

@ -1,5 +1,6 @@
const { processString, processObject, isValid } = require("../src/index.cjs")
const tableJson = require("./examples/table.json")
const dayjs = require("dayjs")
describe("test the custom helpers we have applied", () => {
it("should be able to use the object helper", async () => {
@ -172,6 +173,24 @@ describe("test the date helpers", () => {
const output = await processString("{{ date now 'DD' }}", {})
expect(parseInt(output)).toBe(date.getDate())
})
it("should test the timezone capabilities", async () => {
const date = new Date(1611577535000)
const output = await processString("{{ date time 'HH-mm-ss Z' 'America/New_York' }}", {
time: date.toISOString(),
})
expect(output).toBe("07-25-35 -04:00")
})
it("should guess the users timezone when not specified", async () => {
const date = new Date()
const output = await processString("{{ date time 'Z' }}", {
time: date.toISOString()
})
const timezone = dayjs.tz.guess()
const offset = new dayjs(date).tz(timezone).format("Z")
expect(output).toBe(offset)
})
})
describe("test the string helpers", () => {