【问题标题】:Different time zone support in K6K6 支持不同时区
【发布时间】:2022-08-29 17:50:14
【问题描述】:

我正在尝试使用 K6 获取欧洲/伦敦时区的当前时间。

const date = new Date();

console.log(
    date.toLocaleString('en-GB', {
        timeZone: 'Europe/London',
    }),
);

但看起来它忽略了语言环境并给了我我的机器时区日期和时间。

这就是K6的实现文档中提到的

toLocaleDateString() 方法返回一个带有语言的字符串 此日期的日期部分的敏感表示。新的 语言环境和选项参数让应用程序指定语言 应使用其格式约定并允许自定义 函数的行为。在较旧的实现中,忽略 语言环境和选项参数,使用的语言环境和形式 返回的字符串完全依赖于实现。

【问题讨论】:

    标签: timezone locale k6


    【解决方案1】:

    我相信在 ES6 JS 中没有标准化的方法来做到这一点。但是,我认为您可以通过两种不同的方式来解决此问题。

    或者,您可以按照我们的分步说明将您的 k6 项目与 moment js 库捆绑在一起。这个解决方案是可行的,但是在这个过程中你可能会遇到兼容性问题,因为 k6 的 JS 解释器不是 100% 兼容 ES6 并且可能不支持所有的特性。

    或者,您可以编写一个手动执行时区偏移的小函数。我相信在 ES6 中确实没有标准的方法来做到这一点(请随意指向我显示其他资源的资源):

    function shiftDateTZ(date, utcOffset) {
      // Number of milliseconds since the ECMAscript epoch
      const localTime = date.getTime();
    
      // Difference between local time and UTC time in milliseconds
      const localOffset = date.getTimezoneOffset() * 60000;
    
      // UTC time in milliseconds
      const utc = localTime + localOffset;
    
      // Compute the time for the selected offset to UTC in milliseconds
      const newDateTime = utc + 3600000 * utcOffset;
    
      // Return a new Date object with the offseted time
      return new Date(newDateTime).toLocaleString();
    }
    
    export default function () {
      // Get the current date and time
      const date = new Date();
    
      // Let's look for the time at UTC-4 (New York)
      const offset = -4;
    
      // Shift the date to the selected time zone
      const newDate = shiftDateTZ(date, offset);
    
      // Display the date and time
      console.log(`time in New York: ${newDate}`);
    }
    

    您将要偏移的日期对象和您希望的相对于 UTC 的时区差异传递给函数,它将返回一个与您正在寻找的时区匹配的新 Date 对象。这个函数不像你在 momentJS 中找到的那样用户友好,因为它需要你手动将偏移量传递给你想要将 Date 转换为的时区的 UTC,但它应该是可靠的。

    【讨论】:

    • 感谢奥莱亚德的回答。在运行我的 perf 脚本之前,我正在使用管道/工作流下载 K6。我需要检查捆绑 moment.js 的可行性。
    • 关于您提到的方法,由于夏季英国夏令时的变化,我无法给出联系偏移量。如果是这种情况,我想我将不得不编写一个方法来确定当前日期是否处于夏令时。
    • 不幸的是,我目前想不出一个优雅的解决方案,尤其是不了解有关您的工作流程和特定用例的更多细节:-/
    猜你喜欢
    • 1970-01-01
    • 2015-11-22
    • 2010-12-04
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 2017-11-14
    相关资源
    最近更新 更多