Azim Kamal
Azim Kamal

Reputation: 143

How to add current datetime in POST API request?

I want the start and end date to be in current datetime. I don't know whether it is possible. I need that because I want to trigger the data everyday using my pipeline.

Please see the image here

Upvotes: 7

Views: 24216

Answers (3)

derpirscher
derpirscher

Reputation: 17392

You can create an environment variable in the pre-request-script of the request and then use that variable in the body

var now = new Date();
var timestamp = now.toISOString(); //or whatever format you want.
pm.environment.set("timestamp", timestamp);

alternatively, instead of pm.environment.set you can also use pm.variables.set (like shown in Danny Daintons answer) so the timestamp will only be available in the current request instead of the whole environment.

enter image description here

Upvotes: 14

Danny Dainton
Danny Dainton

Reputation: 25881

You could use moment to make this easier for you. Add this to the pre-request script:

let moment = require('moment');

pm.variables.set('startOfDay', moment().utc().startOf('day').format('YYYY-MM-DD HH:mm:ss'));
pm.variables.set('endOfDay', moment().utc().endOf('day').format('YYYY-MM-DD HH:mm:ss'));

The use the {{startOfDay}} and {{endOfDay}} variables where you need them.

Postman Request

Upvotes: 6

samthecodingman
samthecodingman

Reputation: 26171

You can remove "start" and "end" from the body of the request and then using Postman's Pre-request Script section (next to Body), add the following lines:

// Gets current UTC time in the format "yyyy-MM-dd"
const UTCDate = (new Date()).toISOString().split("T")[0];

// Removes manually set values for "start" and "end", if present
pm.request.body.urlencoded.remove(param => param.key === "start" || param.key === "end");
// Adds a parameter "start" set to UTC midnight
pm.request.body.urlencoded.add({ key: "start", value: `${UTCDate}T00:00:00.000Z` });
// Adds a parameter "end" set to just before UTC midnight of the next day
pm.request.body.urlencoded.add({ key: "end", value: `${UTCDate}T23:59:59.999Z` });

Upvotes: 2

Related Questions