如何在 POST API 请求中添加当前日期时间?

问题描述 投票:0回答:3

我希望开始日期和结束日期为当前日期时间。我不知道是否可以。我需要它,因为我想每天使用我的管道触发数据。

Please see the image here

api postman
3个回答
11
投票

您可以在请求的预请求脚本中创建一个环境变量,然后在正文中使用该变量

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

或者,您也可以使用

pm.environment.set
(如
Danny Daintons
答案中所示)代替 pm.variables.set,因此时间戳仅在 当前请求 中可用,而不是在整个环境中可用。

enter image description here


6
投票

您可以使用

moment
让这对您来说更容易。将其添加到
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'));

在需要的地方使用

{{startOfDay}}
{{endOfDay}}
变量。

Postman Request


2
投票

您可以从请求正文中删除

"start"
"end"
,然后使用 Postman 的 Pre-request Script 部分(位于 Body 旁边),添加以下行:

// 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` });
© www.soinside.com 2019 - 2024. All rights reserved.