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)
15 .find('.timezone-detect')
17 if ($timezone.length) {
18 const dateString = Date();
19 // In some client environments, date strings include a time zone
20 // abbreviation, between 3 and 5 letters enclosed in parentheses,
21 // which can be interpreted by PHP.
22 const matches = dateString.match(/\(([A-Z]{3,5})\)/);
23 const abbreviation = matches ? matches[1] : 0;
25 // For all other client environments, the abbreviation is set to "0"
26 // and the current offset from UTC and daylight saving time status are
27 // used to guess the time zone.
28 const dateNow = new Date();
29 const offsetNow = dateNow.getTimezoneOffset() * -60;
31 // Use January 1 and July 1 as test dates for determining daylight
32 // saving time status by comparing their offsets.
33 const dateJan = new Date(dateNow.getFullYear(), 0, 1, 12, 0, 0, 0);
34 const dateJul = new Date(dateNow.getFullYear(), 6, 1, 12, 0, 0, 0);
35 const offsetJan = dateJan.getTimezoneOffset() * -60;
36 const offsetJul = dateJul.getTimezoneOffset() * -60;
38 let isDaylightSavingTime;
39 // If the offset from UTC is identical on January 1 and July 1,
40 // assume daylight saving time is not used in this time zone.
41 if (offsetJan === offsetJul) {
42 isDaylightSavingTime = '';
44 // If the maximum annual offset is equivalent to the current offset,
45 // assume daylight saving time is in effect.
46 else if (Math.max(offsetJan, offsetJul) === offsetNow) {
47 isDaylightSavingTime = 1;
49 // Otherwise, assume daylight saving time is not in effect.
51 isDaylightSavingTime = 0;
54 // Submit request to the system/timezone callback and set the form
55 // field to the response time zone. The client date is passed to the
56 // callback for debugging purposes. Submit a synchronous request to
57 // avoid database errors associated with concurrent requests
59 const path = `system/timezone/${abbreviation}/${offsetNow}/${isDaylightSavingTime}`;
62 url: Drupal.url(path),
63 data: { date: dateString },