From fd0f3a265b55a9519761256902ea8fa3d0dd568d Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Fri, 11 Mar 2022 21:01:43 -0700 Subject: [PATCH] fix: add timeZone() and fix toOffsetISOString() --- test.js | 25 ++++++++++++++++++++----- xtz.js | 9 ++++++++- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/test.js b/test.js index 483f998..3206402 100644 --- a/test.js +++ b/test.js @@ -4,7 +4,8 @@ var TZ = require("./"); function testUtcToTz(t) { var result = TZ.toTimeZone.apply(TZ, t.inputs).toISOString(); - if (t.result !== result) { + var result2 = TZ.toTimeZoneISOString.apply(TZ, t.inputs); + if (result !== result2 || t.result !== result) { throw new Error( `Invalid UTC/ISO+Offset to TZ conversion for ${t.desc}:\n` + `\tExpected: ${t.result}\n` + @@ -14,10 +15,11 @@ function testUtcToTz(t) { } function testTzToUtc(t) { - var result = TZ.toUTC.apply(TZ, t.inputs); - var result2 = TZ.fromTimeZone.apply(TZ, t.inputs); - if (t.result !== result.toISOString() || t.result !== result2.toISOString()) { - console.log(result); + var result = TZ.fromTimeZone.apply(TZ, t.inputs).toISOString(); + var result2 = TZ.toOffsetISOString.apply(TZ, t.inputs); + var result3 = TZ.toUTC.apply(TZ, t.inputs).toISOString(); + if (t.result !== result || t.result !== result2 || t.result !== result3) { + console.error(result); throw new Error( `Invalid TZ to UTC conversion for ${t.desc}:\n` + `\tExpected: ${t.result}\n` + @@ -317,3 +319,16 @@ console.info( }, ].forEach(testTzToUtc); console.info("Pass: TZ to UTC for America/New_York and Asia/Colombo"); + +var localISOString = TZ.toLocalISOString(); +var reISOString = /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d\.\d\d\d[+-]\d\d\d\d$/; +if (!reISOString.test(localISOString)) { + throw new Error("Couldn't get local time as iso+offset"); +} +console.info("Pass: can get local time as ISO+Offset"); + +var tzName = TZ.timeZone(); +if (!/^[A-Z]\w+\/[A-Z]\w+$/.test(tzName)) { + throw new Error("Couldn't get local Time Zone"); +} +console.info("Pass: can get local timezone"); diff --git a/xtz.js b/xtz.js index 6313dba..96d8d6c 100644 --- a/xtz.js +++ b/xtz.js @@ -103,7 +103,7 @@ } function toOffsetISOString(date, timeZone) { - if ("offset" in date && "year" in date) { + if ("object" === typeof date && "offset" in date && "year" in date) { return formatAsOffsetISOString(date); } @@ -179,6 +179,10 @@ return `${YYYY}-${MM}-${DD}T${hh}:${mm}:${ss}.${sss}${offset}`; } + function getTimeZone() { + return new Intl.DateTimeFormat().resolvedOptions().timeZone; + } + exports.XTZ = { // bespoke date => // 2021-11-07T3:15:59-0500 @@ -190,6 +194,9 @@ // -240 => -0400 formatOffset: formatOffset, + // "America/New_York" + timeZone: getTimeZone, + // "2021-11-07T03:15:59-0500" toLocalISOString: toLocalISOString, // [ "2021-11-07T08:15:59Z", "America/New_York" ]