javascript - 使用 CET 作为默认时区在 javascript 中解析日期

标签 javascript date parsing timezone timezone-offset

我有一些遗留的网络服务有时不会本地化日期。有时他们会这样做,所以我必须支持这两种情况。

它们应始终使用意大利的语言环境(标准时间为 UTC+1,夏令时为 UTC+2),但有时它们返回的日期会在日期 ISO 字符串末尾省略时区。

例如,意大利新年应该是 2018-01-01T00:00:00+0100 而他们只返回 2018-01-01T00 :00:00

这会导致 Javascript 出现不良行为,尤其是在处理其他时区的截止日期和客户时。

我希望能够编写一段代码来解析 ISO 格式的日期字符串,如果没有指定时区则假定为意大利本地化。

我的代码几乎没问题(它不解析毫秒,但我可以忍受),不幸的是,当浏览器在没有夏令时的时区执行时,它悲惨地失败了。我应该怎么办?我错过了什么吗?

提前致谢

/**
 * Get the local timezone using standard time (no daylight saving time).
 */
Date.prototype.stdTimezoneOffset = function() {
  var jan = new Date(this.getFullYear(), 0, 1);
  var jul = new Date(this.getFullYear(), 6, 1);
  return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}

/**
 * Check whether current time is daylight saving time.
 */
Date.prototype.isDst = function() {
  return this.getTimezoneOffset() < this.stdTimezoneOffset();
}

/**
 * Check whether daylight saving time is observed in current timezone.
 */
Date.prototype.isDstObserved = function() {
  var jan = new Date(this.getFullYear(), 0, 1);
  var jul = new Date(this.getFullYear(), 6, 1);
  return jan.getTimezoneOffset() != jul.getTimezoneOffset();
}

/**
 * Cross-browser parse of a date using CET as default timezone.
 */
Date.parseFromCET = function(str) {
  if (str == null) return null;

  // split the input string into an array of integers
  var a = str.split(/[^0-9]/)
    .map(function(s) {
      return parseInt(s, 10)
    });

  var b = new Date(
    a[0], // yyyy
    a[1] - 1 || 0, // MM
    a[2] || 1, // dd
    a[3] || 0, // hh
    a[4] || 0, // mm
    a[5] || 0 // ss
  );

  // if no timezone is present, force to CET
  if (str.lastIndexOf('-') <= 7 && str.indexOf('+') == -1 && str.indexOf('Z') == -1) {
    var CET_timezone_offset = b.isDst() ? '+0200' : '+0100'
    var isoString = a[0] + '-' + a[1] + '-' + a[2] + 'T' +
      a[3] + ':' + a[4] + ':' + a[5] + CET_timezone_offset;
    return Date.parseFromCET(isoString);
  }

  // remove local timezone offset to go from UTC time to local time
  b.setMinutes(b.getMinutes() - b.getTimezoneOffset());

  // add/remove forced timezone offset to calculate exact local time
  if (str.indexOf('+') > -1) {
    let hours = Math.floor(a[a.length - 1] / 100);
    let minutes = a[a.length - 1] % 100;
    b.setMinutes(b.getMinutes() - minutes);
    b.setHours(b.getHours() - hours);
  }
  if (str.lastIndexOf('-') > 7) {
    let hours = Math.floor(a[a.length - 1] / 100);
    let minutes = a[a.length - 1] % 100;
    b.setMinutes(b.getMinutes() + minutes);
    b.setHours(b.getHours() + hours);
  }
  return b;
}

最佳答案

时间戳与 ECMA-262 中的格式不一致,因为它在偏移量中缺少一个冒号。因此解析依赖于实现,您可能会得到一个无效日期(例如在 Safari 中)。

罗马的标准偏移量是 +01:00。夏令时从 3 月最后一个星期日的 02:00 开始(更改为 +02:00),到 10 月最后一个星期日的 02:00 结束(返回 +01:00)。

请注意,历史上已经发生了变化。意大利于 1916 年开始使用夏令时,但也有一段时间没有遵守。自 1965 年以来一直在观察,所以只要您的日期在此之后,您就不必担心过去的变化,只担心 future 的变化。

以下是一种解决方法,它需要更多的测试并且应该对输入字符串和生成的 Date 对象进行验证。您可能还应该处理时区“Z”。

如果您要经常这样做,管理时区的库将大有帮助,因为它还应该处理过去和 future 的历史变化。

/** Get a Date for the last Sunday of the month
 *  @param {number|string} year - year for month
 *  @param {number|string} month - calendar month number, 1 = Jan, 2 = Feb, etc.
 *  @returns {Date} date for last Sunday for given year and month
 */
function getLastSunday(year, month) {
  // Date for last day of month
  var d = new Date(Date.UTC(year, month, 0));
  // Adjust to previous Sunday
  d.setUTCDate(d.getUTCDate() - d.getUTCDay());
  return d;
}

/** Return a date set to the UTC start of Italian DST
 *  Starts at +0300 UTC on the last Sunday in March
 *
 *  @param {number|string} year to get start of DST for
 *  @returns {Date} set to start date and +0300Z
 */
function getDSTStart(year) {
  var d = getLastSunday(year, 3);
  d.setUTCHours(3);
  return d;
}

/** Return a date set to the UTC end of Italian DST
 *  Ends at +0400 UTC on the last Sunday in October
 *
 *  @param {number|string} year to get start of DST for
 *  @returns {Date} set to start date and +0400Z
 */
function getDSTEnd(year) {
  var d = getLastSunday(year, 10);
  d.setUTCHours(4);
  return d;
}

/** Given a year, month, day and hour, return
 *  true or false depending on whether DST is
 *  being observed in Italy.
 *  Use UTC to avoid local influences, assume standard time
 *
 *  @param {number|string} year  - subject year
 *  @param {number|string} month - subject calendar month
 *  @param {number|string} day   - subject day
 *  @param {number|string} hour  - subject hour
 *  @returns {number} offset for provided date and time
 */
function getItalianOffset(year, month, day, hour) {
  var d = new Date(Date.UTC(year, month-1, day, +hour + 1));
  return d >= getDSTStart(year) && d < getDSTEnd(year)? '+0200' : '+0100';
}

/** Convert offset in format +0000 to minutes
 *  EMCAScript offset has opposite sign
 *
 *  @param {string} offset - in format +/-HHmm
 *  @reaturns {number} offset in minutes, + for west, - for east
 */
function offsetToMins(offset) {
    sign = /^\+/.test(offset)? -1 : 1;
    tz   = 60 * offset.slice(-4, -2) + (1 * offset.slice(-2));
    tz  *= sign;
    return tz;
}

/** Parse timestamp that may or may not have a timezone.
 *  If no timezone, assume Italian timezone (+0100), adjusting for
 *  daylight saving.
 *  DST starts at +0300Z on last Sunday in March
 *  DST ends at +0400Z on last Sunday in October
 *  2018-01-01T00:00:00+0100 or 2018-01-01T00:00:00
 */
function parseItalianDate(s) {
  var b = s.split(/\D/);
  var hasTz = /[+-]\d{4}$/.test(s);
  var d, sign, tz;

  // If has offset, get from string
  // Otherwise, calculate offset
  if (hasTz) {
    tz = s.slice(-5);
  } else {
    tz = getItalianOffset(b[0], b[1], b[2], b[3]);
  }

  // Create Date using correct offset
  d = new Date(Date.UTC(b[0], b[1]-1, b[2], b[3], b[4], b[5]));
  d.setUTCMinutes(d.getUTCMinutes() + offsetToMins(tz));
  
  return d;
}

// Tests
['2018-01-01T00:00:00',     // New year
 '2018-03-25T01:00:00',     // One hour before change over
 '2018-03-25T03:00:00',     // One hour after change over
 '2018-03-25T01:00:00+0100',// As above but with timzone offset
 '2018-03-25T03:00:00+0200',
 '2018-10-27T03:00:00',     // Still in DST
 '2018-10-28T03:00:00',     // After DST ended
 '2018-10-28T03:00:00+0100'
].forEach(function(s) {
  console.log(`${s} => ${formatDate(parseItalianDate(s))}`);
});

// Helper to format a date in Europe/Rome timezone
function formatDate(d) {
  return d.toLocaleString('en-GB',{
    year   : 'numeric',
    month  : 'short',
    day    : '2-digit',
    weekday: 'short',
    hour   : '2-digit',
    minute : '2-digit',
    second : '2-digit',
    hour12 : 'false',
    timeZone: 'Europe/Rome',
    timeZoneName: 'short'
  });
}

关于javascript - 使用 CET 作为默认时区在 javascript 中解析日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51388638/

相关文章:

java - ANTLR,表达式语法问题

php - 解析 simple_html_dom 结果

git - 如何将修订和构建日期添加到源?

java - SimpleDateFormat 对象中 MMM 和 LLL(独立值)之间的区别

javascript - 当另一个 PHP 脚本运行时,AJAX 不会调用它的 PHP 脚本

javascript - 如果列只有一项,如何删除标签

java - 如何从 java.sql.Timestamp 转换为 java.util.Date?

parsing - NSIS 替换文件 : Never reads file & never identifies the correct line 中的行

javascript - 使用 Handlebars 模板引擎传递 JSON 数组

javascript - Google Sheets 脚本——如何引用给定行的单元格?