Chris@0: /** Chris@0: * @file Chris@0: * Timezone detection. Chris@0: */ Chris@0: Chris@17: (function($, Drupal) { Chris@0: /** Chris@0: * Set the client's system time zone as default values of form fields. Chris@0: * Chris@0: * @type {Drupal~behavior} Chris@0: */ Chris@0: Drupal.behaviors.setTimezone = { Chris@0: attach(context, settings) { Chris@17: const $timezone = $(context) Chris@17: .find('.timezone-detect') Chris@17: .once('timezone'); Chris@0: if ($timezone.length) { Chris@0: const dateString = Date(); Chris@0: // In some client environments, date strings include a time zone Chris@0: // abbreviation, between 3 and 5 letters enclosed in parentheses, Chris@0: // which can be interpreted by PHP. Chris@0: const matches = dateString.match(/\(([A-Z]{3,5})\)/); Chris@0: const abbreviation = matches ? matches[1] : 0; Chris@0: Chris@0: // For all other client environments, the abbreviation is set to "0" Chris@0: // and the current offset from UTC and daylight saving time status are Chris@0: // used to guess the time zone. Chris@0: const dateNow = new Date(); Chris@0: const offsetNow = dateNow.getTimezoneOffset() * -60; Chris@0: Chris@0: // Use January 1 and July 1 as test dates for determining daylight Chris@0: // saving time status by comparing their offsets. Chris@0: const dateJan = new Date(dateNow.getFullYear(), 0, 1, 12, 0, 0, 0); Chris@0: const dateJul = new Date(dateNow.getFullYear(), 6, 1, 12, 0, 0, 0); Chris@0: const offsetJan = dateJan.getTimezoneOffset() * -60; Chris@0: const offsetJul = dateJul.getTimezoneOffset() * -60; Chris@0: Chris@0: let isDaylightSavingTime; Chris@0: // If the offset from UTC is identical on January 1 and July 1, Chris@0: // assume daylight saving time is not used in this time zone. Chris@0: if (offsetJan === offsetJul) { Chris@0: isDaylightSavingTime = ''; Chris@0: } Chris@0: // If the maximum annual offset is equivalent to the current offset, Chris@0: // assume daylight saving time is in effect. Chris@0: else if (Math.max(offsetJan, offsetJul) === offsetNow) { Chris@0: isDaylightSavingTime = 1; Chris@0: } Chris@0: // Otherwise, assume daylight saving time is not in effect. Chris@0: else { Chris@0: isDaylightSavingTime = 0; Chris@0: } Chris@0: Chris@0: // Submit request to the system/timezone callback and set the form Chris@0: // field to the response time zone. The client date is passed to the Chris@0: // callback for debugging purposes. Submit a synchronous request to Chris@0: // avoid database errors associated with concurrent requests Chris@0: // during install. Chris@0: const path = `system/timezone/${abbreviation}/${offsetNow}/${isDaylightSavingTime}`; Chris@0: $.ajax({ Chris@0: async: false, Chris@0: url: Drupal.url(path), Chris@0: data: { date: dateString }, Chris@0: dataType: 'json', Chris@0: success(data) { Chris@0: if (data) { Chris@0: $timezone.val(data); Chris@0: } Chris@0: }, Chris@0: }); Chris@0: } Chris@0: }, Chris@0: }; Chris@17: })(jQuery, Drupal);