LP1840782 Date to translate parts into a timezone-aware date user/berick/lp1840782-date-time-native-widgets
authorBill Erickson <berickxx@gmail.com>
Sat, 24 Aug 2019 17:51:45 +0000 (13:51 -0400)
committerBill Erickson <berickxx@gmail.com>
Sat, 24 Aug 2019 17:51:45 +0000 (13:51 -0400)
Signed-off-by: Bill Erickson <berickxx@gmail.com>
Open-ILS/src/eg2/src/app/share/util/date.ts
Open-ILS/src/eg2/src/app/staff/sandbox/sandbox.component.ts

index c8a9ffd..423fcd0 100644 (file)
@@ -100,7 +100,7 @@ export class DateUtil {
 
         // The locale "en-US" is used here because it allows the
         // formatter to produce numeric values that are parseable by JS
-        // Date objects / components.
+        // Date objects and other date/time components.
         const formatter = Intl.DateTimeFormat('en-US', formatOps);
         const parts = formatter.formatToParts();
         const response: DateParts = new DateParts();
@@ -111,6 +111,37 @@ export class DateUtil {
 
         return response;
     }
+
+    // Returns a date object equivalent to the provided date parts
+    // and time zone.  The resulting date will be a standard JS Date
+    // object, expressed in the local time zone.
+    //
+    // For example, assuming the browser time zone is America/New_York,
+    // this would turn parts for "America/Los_Angeles"
+    // {year: 2019, month: 08, day: 24, hour: 12, minute: 00}
+    // into 2019-08-24 15:00:00-0400, i.e. the local date equivalent.
+    static datePartsToDate(parts: DateParts, timeZone: string): Date {
+
+        // Create a date from the parts in the local time zone
+        const localDate = new Date(
+            parts.year, parts.month, parts.day, parts.hour, parts.minute);
+
+        // Shift the date by transforming it into the requested time zone
+        const offsetParts = DateUtil.dateToParts(localDate, timeZone);
+
+        // Turn the shifted parts into another local date.
+        const offsetDate = new Date(offsetParts.year, offsetParts.month,
+            offsetParts.day, offsetParts.hour, offsetParts.minute);
+
+        // The difference between the two is the difference that must
+        // be applied to dates in the local time zone to represent
+        // the requetsed date parts from the requested time zone.
+        const offset = localDate.getTime() - offsetDate.getTime();
+
+        localDate.setTime(localDate.getTime() + offset);
+
+        return localDate;
+    }
 }
 
 
index 072965f..c6080e3 100644 (file)
@@ -411,6 +411,8 @@ export class SandboxComponent implements OnInit {
         const d = new Date();
         this.dateString = DateUtil.dateToLocaleString(d, options);
         this.dateParts = DateUtil.dateToParts(d, this.dateTimeZone);
+
+        console.log(DateUtil.datePartsToDate(this.dateParts, 'America/Los_Angeles'));
     }
 }