Skip to content

Commit

Permalink
feat: add function isValidTimezone
Browse files Browse the repository at this point in the history
  • Loading branch information
lhermann committed Jul 11, 2024
1 parent 37c0159 commit c6fb20f
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ export { default as formatTimezone } from './formatTimezone.js'
export { default as isSameDay } from './isSameDay.js'
export * from './formatTimeOfDay.js'
export * from './dhmsToDigits.js'
export * from './isValidTimezone.js'
26 changes: 26 additions & 0 deletions isValidTimezone.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Checks if a given time zone is valid.
*
* This function verifies whether a given time zone identifier is valid by
* attempting to create a DateTimeFormat object with the provided time zone.
*
* @param {string} tz - The time zone identifier to be validated.
* @returns {boolean} - Returns true if the time zone is valid, otherwise false.
* @throws {Error} - Throws an error if the environment does not support time zones.
*
* @example
* isValidTimeZone('America/New_York') // true
* isValidTimeZone('Invalid/Timezone') // false
*/
export function isValidTimezone (tz) {
if (!Intl || !Intl.DateTimeFormat().resolvedOptions().timeZone) {
throw new Error('Time zones are not available in this environment')
}

try {
Intl.DateTimeFormat(undefined, {timeZone: tz})
return true
} catch {
return false
}
}
30 changes: 30 additions & 0 deletions tests/isValidTimezone.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { expect } from 'chai'
import { isValidTimezone } from '../index.js'

describe('isValidTimezone', () => {
it('should return true for a valid time zone', () => {
expect(isValidTimezone('America/New_York')).to.be.true
})

it('should return false for an invalid time zone', () => {
expect(isValidTimezone('Invalid/Timezone')).to.be.false
})

it('should return false for a valid GMT offset', () => {
expect(isValidTimezone('GMT+01:00')).to.be.false
})

it('should throw an error if time zones are not available in the environment', () => {
const originalIntl = global.Intl

// Mock the absence of Intl
global.Intl = undefined

try {
expect(() => isValidTimezone('America/New_York')).to.throw('Time zones are not available in this environment')
} finally {
// Restore the original Intl object
global.Intl = originalIntl
}
})
})

0 comments on commit c6fb20f

Please sign in to comment.