timezone.js 2.5 KB

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