walltime-js
Version:
A javascript library for easily translating a UTC time to a "Wall Time" for a particular time zone and back.
120 lines (80 loc) • 3.99 kB
text/coffeescript
init = (helpers, rule, zone) ->
class WallTime
init: (rules = {}, zones = {}) ->
= {}
= {}
rules, zones
= null
= null
= true
addRulesZones: (rules = {}, zones = {}) ->
currZone = null
for own zoneName, zoneVals of zones
newZones = []
currZone = null
for z in zoneVals
newZone = new zone.Zone(z.name, z._offset, z._rule, z.format, z._until, currZone)
newZones.push newZone
currZone = newZone
[zoneName] = newZones
for own ruleName, ruleVals of rules
newRules = (new rule.Rule(r.name, r._from, r._to, r.type, r.in, r.on, r.at, r._save, r.letter) for r in ruleVals)
[ruleName] = newRules
setTimeZone: (name) ->
if !
throw new Error "Must call init with rules and zones before setting time zone"
if ![name]
throw new Error "Unable to find time zone named #{name || '<blank>'}"
matches = [name]
= new zone.ZoneSet(matches, (ruleName) => [ruleName])
= name
Date: (y, m = 0, d = 1, h = 0, mi = 0, s = 0, ms = 0) ->
y or= new Date().getUTCFullYear()
helpers.Time.MakeDateFromParts y, m, d, h, mi, s, ms
UTCToWallTime: (dt, zoneName = ) ->
if typeof dt == "number"
dt = new Date(dt)
if zoneName !=
zoneName
if !
throw new Error "Must set the time zone before converting times"
.getWallTimeForUTC dt
WallTimeToUTC: (zoneName = , y, m = 0, d = 1, h = 0, mi = 0, s = 0, ms = 0) ->
if zoneName !=
zoneName
wallTime = if typeof y == "number" then helpers.Time.MakeDateFromParts y, m, d, h, mi, s, ms else y
.getUTCForWallTime wallTime
IsAmbiguous: (zoneName = , y, m, d, h, mi = 0) ->
if zoneName !=
zoneName
wallTime = if typeof y == "number" then helpers.Time.MakeDateFromParts y, m, d, h, mi else y
.isAmbiguous wallTime
# NOTE: Exporting an instantiated WallTime object.
new WallTime
if typeof window == 'undefined'
req_zone = require "./olson/zone"
req_rule = require "./olson/rule"
req_help = require "./olson/helpers"
module.exports = init(req_help, req_rule, req_zone)
else if typeof define != 'undefined'
# If walltime-data is not defined, automatically define so we can load
unless require.specified 'walltime-data'
console?.warn?("To use WallTime with requirejs please include the walltime-data.js script before requiring walltime")
define 'walltime-data', [], ->
null
define ['olson/helpers', 'olson/rule', 'olson/zone', 'walltime-data'], (dep_help, dep_rule, dep_zone, WallTimeData) ->
lib = init dep_help, dep_rule, dep_zone
if WallTimeData?.zones
lib.init WallTimeData.rules, WallTimeData.zones
lib
else
or= {}
# Some trickery here because we want a clean window.WallTime api,
# But still have to keep the .helpers etc.
api = init(.helpers, .rule, .zone)
for own key,val of
api[key] = val
= api
# Check for and initialize with the passed in data.
if .autoinit and .data?.rules and .data?.zones
.init .data.rules, .data.zones