6 (function ($, Drupal) {
8 * Set the client's system time zone as default values of form fields.
10 * @type {Drupal~behavior}
12 Drupal.behaviors.setTimezone = {
13 attach(context, settings) {
14 const $timezone = $(context).find('.timezone-detect').once('timezone');
15 if ($timezone.length) {
16 const dateString = Date();
17 // In some client environments, date strings include a time zone
18 // abbreviation, between 3 and 5 letters enclosed in parentheses,
19 // which can be interpreted by PHP.
20 const matches = dateString.match(/\(([A-Z]{3,5})\)/);
21 const abbreviation = matches ? matches[1] : 0;
23 // For all other client environments, the abbreviation is set to "0"
24 // and the current offset from UTC and daylight saving time status are
25 // used to guess the time zone.
26 const dateNow = new Date();
27 const offsetNow = dateNow.getTimezoneOffset() * -60;
29 // Use January 1 and July 1 as test dates for determining daylight
30 // saving time status by comparing their offsets.
31 const dateJan = new Date(dateNow.getFullYear(), 0, 1, 12, 0, 0, 0);
32 const dateJul = new Date(dateNow.getFullYear(), 6, 1, 12, 0, 0, 0);
33 const offsetJan = dateJan.getTimezoneOffset() * -60;
34 const offsetJul = dateJul.getTimezoneOffset() * -60;
36 let isDaylightSavingTime;
37 // If the offset from UTC is identical on January 1 and July 1,
38 // assume daylight saving time is not used in this time zone.
39 if (offsetJan === offsetJul) {
40 isDaylightSavingTime = '';
42 // If the maximum annual offset is equivalent to the current offset,
43 // assume daylight saving time is in effect.
44 else if (Math.max(offsetJan, offsetJul) === offsetNow) {
45 isDaylightSavingTime = 1;
47 // Otherwise, assume daylight saving time is not in effect.
49 isDaylightSavingTime = 0;
52 // Submit request to the system/timezone callback and set the form
53 // field to the response time zone. The client date is passed to the
54 // callback for debugging purposes. Submit a synchronous request to
55 // avoid database errors associated with concurrent requests
57 const path = `system/timezone/${abbreviation}/${offsetNow}/${isDaylightSavingTime}`;
60 url: Drupal.url(path),
61 data: { date: dateString },