Different time zone support in K6

Viewed 37

Im trying to get the current time in Europe/London time zone using K6.

const date = new Date();

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

But it looks like it ignores the locale and gives me my machine timezone date and time.

This is what is mentioned in the implementation document of K6

The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date. The new locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.

1 Answers

I believe there is no standardized way to do this in ES6 JS. However, I think you can approach this in two different ways.

Either, you could bundle your k6 project with the moment js library as described in our step by-step instructions. This solution could work, but you might encounter compatibility issues in the process, as k6’s JS interpreter is not 100% compliant with ES6 and might not support all the features’ moment depends on.

Or, you could write a tiny function that does the timezone offsetting manually. I believe there is no standard way of doing this in ES6, indeed (feel free to point me to resources showing otherwise):

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}`);
}

You pass the function the date object you want to offset from and the timezone difference relative to UTC you wish, and it will return a new Date object matching the timezone you’re looking for. This function is not as user-friendly as what you’d find in momentJS as it requires you to manually pass the offset to UTC of the timezone you would like to convert the Date to, but it should be reliable.

Related