How to get local time of different timezone in Postman?

Viewed 12810

I want to get local time of Rome time zone. Didn't find any details on how to use moment sandbox built-in library in postman documentation here postman_sandbox_api_reference

what I have tried so far

var moment = require('moment');
console.log(moment().tz(environment.TimeZone).format());

error it throws - TypeError | moment(...).tz is not a function

another attempt-

var moment = require('moment-timezone');
console.log(moment().tz(environment.TimeZone).format());

error it throws - Error | Cannot find module 'moment-timezone'

Where I'm going wrong? can anyone point me in right direction.

Thanks

2 Answers

Postman only has the moment library built-in and not moment-timezone.

If what you're doing isn't part of the moment docs, it's not going to work.

https://momentjs.com/docs/

As a workaround to get the data, you could use a simple 3rd party API.

Making a request to this endpoint would get you some timezone data that you could use.

http://worldtimeapi.org/api/timezone/Europe/Rome

This could be added to the pm.sendRequest() in the pre-request script to fetch the data you require and use this in another request.

pm.sendRequest("http://worldtimeapi.org/api/timezone/Europe/Rome", function (err, res) {
    pm.globals.set("localTimeRome", res.json().datetime);
});

Actually, you can write a simple function to get local time in other time zones only with moment:

const moment = require('moment');

const TimeZoneUTCOffsetMapping = {
  'America/Chicago': -6,
  'Europe/Rome': 2,
  'Asia/Shanghai': 8,
  ...
};

const LocalUTCOffset = 8;

function getMomentDisplayInTimeZone(momentObj, timeZone) {
  let timeZoneUTCOffset = TimeZoneUTCOffsetMapping[timeZone];
  if (timeZoneUTCOffset === undefined) {
    throw new Error('No time zone matched');
  }

  return momentObj.add(timeZoneUTCOffset - LocalUTCOffset, 'hour').format('YYYY-MM-DDTkk:mm:ss');
}

console.log(getMomentDisplayInTimeZone(moment(), 'Europe/Rome'));
Related