Converting $timestamp to ISO 8601

How can I convert $timestamp to ISO8601 format in a pre-request script?

This page on Stack Overflow has a function to do it, but neither Date() nor toISOString() seem to be available.

1 Like

Dynamic variables (like $timestamp) cannot be used in the Sandbox. You can only use them in the {{..}} format in the request URL / headers / body.
https://learning.getpostman.com/docs/postman/environments_and_globals/variables/#dynamic-variables.

Try:

var dateIso = new Date().toISOString();

Good reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString

2 Likes

Me too!! I mean… for all ISO date needs, I fall back to the code snippet that @matt posted.

However, if I have to do heavy date lifting, Postman Sandbox has the powerful β€œmoment” library built in - more at https://momentjs.com/

var moment = require('moment');
moment().format();

Docs of moment: http://momentjs.com/docs/#/displaying/as-iso-string/

2 Likes

Thank you. That worked beautifully!

@shamasis, Thank you, I’ll check that when I have some free time.

Moment is pretty great.

I use this pre-request snippet to generate a timestamp from the previous day:

var moment = require('moment');
var ISO_8601_OFFSET = 'YYYY-MM-DDTHH:mm:ss.SSS';
var momentdate = moment().subtract(1, 'days').format(ISO_8601_OFFSET);

pm.environment.set("timestampUtcIso8601", momentdate+'Z');

Awesome stuff @murdoc-she-wrote,

You could reduce that down even further :wink:

var moment = require('moment');
pm.environment.set("timestampUtcIso8601more", `${moment().subtract(1, 'days').format()}Z`);
3 Likes

Just updating in case someone goes to use moment. This is now as Moment.js describe in their documentation a β€œdone” project, they will not be updating it in the future. More info: Moment.js | Docs

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.