timezone.es6.js 2.7 KB

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