timezone.js 2.7 KB

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