timezone.es6.js 2.7 KB

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