【问题标题】:Get milliseconds for custom date in custom timezone获取自定义时区中自定义日期的毫秒数
【发布时间】:2021-12-21 08:18:51
【问题描述】:

我有一个在欧洲/莫斯科时区工作的日期服务器 API。所选日期必须作为欧洲/莫斯科时区的时间戳从客户端发送。

一位来自加拿大的客户在日历中选择一个日期,例如 2011 年 11 月 8 日,必须发送欧洲/莫斯科时区的时间戳。

我可以通过moment.js解决这个问题,但是很遗憾,由于某些原因,我不能在项目中使用第三方库。

基本上我需要一个与 moment.tz 方法做同样事情的函数:

moment.tz('2021-11-08T00:00:00', '欧洲/莫斯科');

【问题讨论】:

    标签: javascript date timezone


    【解决方案1】:

    您可以使用 Intl.DateTimeFormat 和合适的选项来获取任何 IANA 位置的时间戳。 formatToParts 方法获取所需的值,然后只需对它们进行格式化即可。例如

    function toLocTimestamp(loc, date = new Date()) {
      let {year, month, day, hour, minute, second, timeZoneName} = new Intl.DateTimeFormat('en', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
        timeZone: loc,
        timeZoneName: 'short'
      }).formatToParts().reduce((parts, part) => {
        parts[part.type] = part.value;
        return parts;
      }, Object.create(null));
      
      // Check if timezone not offset and fix
      if (!/\d/.test(timeZoneName)) {
        timeZoneName = date.toLocaleString('fr',{
          hour: 'numeric',
          timeZone: loc,
          timeZoneName: 'short'
        }).match(/\S+$/)[0];
      }
      // Change timeZoneName to offset
      let sign = timeZoneName.substring(3,4);
      let offset = timeZoneName.substring(4);
      let [offH, offM] = offset.split(':');
      // Return timestamp
      return `${year}-${month}-${day}T${hour}:${minute}:${second}${sign}${offH.padStart(2,'0')}:${offM || '00'}`;
    }
    
    // E.g.
    ['Europe/Moscow', 'Asia/Kolkata','Australia/Lord_Howe',
     'America/St_Johns'].forEach(
      loc => console.log(`${loc.padEnd(20,' ')}: ${toLocTimestamp(loc)}`)
     );

    timeZoneName 修复是必需的,因为根据传递给 dateTimeFormat 的语言和主机系统语言,偏移量可能是 GMT±H[:mm]、UTC±H [:mm] 或“ChST”或“CET”之类的缩写。如果 en 返回缩写,则 fr 不应该。

    这将观察不同位置的 DST。如果需要固定的偏移量,只需通过偏移量调整 UTC 时间,使用 toISOString 获取时间戳并去除尾随的 Z。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-08
      • 1970-01-01
      • 2021-05-31
      • 2012-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多