> 技术文档 > 如何在postman使用时间戳_postman时间戳

如何在postman使用时间戳_postman时间戳


1. 使用 Pre-request Script 动态转换

在发送请求前,将日期字符串转为时间戳并存储为环境变量/全局变量。

示例代码
// 将日期字符串(如 \"2023-10-01\")转为时间戳(毫秒)const dateString = \"2023-10-01\"; // 可以是变量或固定值const timestamp = new Date(dateString).getTime();// 存储到环境变量中pm.environment.set(\"timestamp\", timestamp);// 如果需要秒级时间戳pm.environment.set(\"timestamp_seconds\", Math.floor(timestamp / 1000));
使用变量

在请求的 URL、Body 或 Headers 中通过 {{timestamp}} 引用:

GET https://api.example.com/data?timestamp={{timestamp}}

2. 在请求体中直接使用(JSON Body)​

如果 API 需要 JSON 格式的时间戳,可以在 Body 中动态生成:

// Pre-request Scriptconst timestamp = new Date(\"2023-10-01\").getTime();pm.environment.set(\"timestamp\", timestamp);

然后在 ​Body → raw → JSON​ 中引用变量:

{ \"date\": \"2023-10-01\", \"timestamp\": {{timestamp}}}

3. 使用 Tests Script 处理响应数据

如果响应中包含日期字符串,可以在 Tests 脚本中转换并测试:

// 假设响应返回 { \"date\": \"2023-10-01\" }const responseData = pm.response.json();const timestamp = new Date(responseData.date).getTime();// 打印到控制台console.log(\"Timestamp:\", timestamp);// 断言时间戳是否有效pm.test(\"Timestamp is valid\", () => { pm.expect(timestamp).to.be.a(\'number\');});

常见日期格式转换示例

日期字符串格式 转换代码(毫秒) 输出示例(毫秒) \"2023-10-01\" new Date(\"2023-10-01\").getTime() 1696118400000 \"2023-10-01T12:00:00Z\" new Date(\"2023-10-01T12:00:00Z\").getTime() 1696161600000 当前时间 new Date().getTime() 动态值

注意事项

  1. 时区问题

    • new Date(\"2023-10-01\") 会解析为本地时区的午夜(UTC+8 会转为前一天的 UTC 时间)。
    • 明确时区时,建议使用 ISO 格式(如 \"2023-10-01T00:00:00Z\")。
  2. 无效日期处理
    添加校验逻辑:

    const date = new Date(\"invalid-date\");if (isNaN(date.getTime())) { throw new Error(\"Invalid date string!\");}
  3. 秒级时间戳
    如果 API 需要秒级时间戳(如 Unix 时间戳),需除以 1000:

    Math.floor(new Date().getTime() / 1000)

示例截图

  1. Pre-request Script 设置时间戳
    https://assets.postman.com/postman-docs/pre-request-script.png

  2. 在请求中引用变量
    https://assets.postman.com/postman-docs/use-environment-variable.png

通过以上方法,你可以灵活地在 Postman 中处理日期与时间戳的转换!