在 Postman 中,时间戳的处理对于 API 请求和响应的调试和测试至关重要,正确处理时间戳可以确保数据的准确性和一致性,而 Moment 库和原生 JS 是两种常见的处理方式。此外,我们还将介绍 Apifox,它提供了更直观、更简便的时间戳处理方法,详情见下文。
1.通过 Moment 库转换时间戳
Postman 中内置了 Moment 库,可以通过 Moment 库提供的moment.unix(Number)
方法进行转换,参考脚本如下:
let timestamp = Math.floor(Date.now() / 1000);
let moment = require("moment");
// 直接使用时间戳创建 moment 对象并格式化
let formattedDate = moment.unix(timestamp).format("YYYY-MM-DD HH:mm:ss");
console.log(formattedDate);

转换之后,你可以将其添加到环境变量中,以供取用,参考脚本如下(加入到上面的脚本之后):
// 将时间戳添加到环境变量中
pm.environment.set('current_timestamp', timestamp);
// 将格式化后的日期添加到请求中
pm.environment.set('current_date', formatDate(timestamp));
2.通过原生 JS 转换时间戳
原生 JS 转换时间戳需要的代码有点多,容易混乱,不做推荐。参考如下:
let timestamp = Math.floor(Date.now() / 1000);
function formatTimestamp(timestamp) {
const date = new Date(timestamp * 1000);
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
return formattedDate;
}
const formattedDate = formatTimestamp(timestamp);
console.log(formattedDate);

比 Postman 更好用的工具:Apifox
在 Apifox 中转换时间戳更加方便。如果你需要在请求中携带时间戳,那么可以通过【动态值】来直接获取。
在项目的接口请求参数的【示例值】那里,点击一个像“魔棒”的图标,然后依次点击【数据生成器->时间戳】,在发送请求时即可获取到当前时间的时间戳。


当然,你也可以通过脚本直接获取:

如果需要对时间戳进行转换,也可以像 Postman 一样编写脚本,Apifox 中的脚本语法兼容 Postman,可以无缝切换过来。

或者还是通过可视化【动态值】的方式,直接生成。

总结
在 Postman 中,时间戳可通过 Moment 库或原生 JS 转换。Moment 库操作简便,内置于 Postman,提供了 moment.unix(Number)
方法;而原生 JS 代码稍繁琐。另有 Apifox 工具,可直接获取时间戳或通过脚本转换,且与 Postman 兼容。总体而言,Moment 库与 Apifox 更为便捷,但 Apifox 在时间戳获取方面更为直接。

知识扩展: