Postman使用js获取日期

时间:2023-11-10 17:34:26

在用postman进行接口自动化测试的时候,某个查询接口需要使用到日期参数进行请求;

假设当前日期为2018-05-07 10:30:20 ,需要传的日期为:

beginTime:2018-05-01 00:00:00;

endTime:2018-05-07 23:59:59;

获取日期,具体代码如下:

function beginTime(){
  //获取当前日期
  var date = new Date();
  //获取当前日期前6天;
  date.setDate(date.getDate()-6);
  var Y = date.getFullYear()+'';
  var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1):date.getMonth()+1+'');//获取当前月份,js中月份从0开始,所以要+1;
  var D = (date.getDate() < 10 ? '0'+date.getDate():date.getDate()+'');
  return Y+'-'+M+'-'+D+' '+'00:00:00';
}
pm.environment.set("beginTime",beginTime());
function endTime(){
var date = new Date();
var Y = date.getFullYear();
var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1):date.getMonth()+1+'');
var D = (date.getDate() < 10 ? '0'+date.getDate():date.getDate()+'');
return Y+'-'+M+'-'+D+' '+'23:59:59';
}
pm.environment.set("endTime",endTime());

 获取时间戳,具体代码如下:

//直接获取当前时间戳
var gameHoldBeginTime = Date.parse(new Date());
pm.environment.set("gameHoldBeginTime",gameHoldBeginTime); //获取N天后的时间戳
var date = new Date();
var timestamp1 = Date.parse(new Date());
gameHoldEndTime = timestamp1 + 86400000 * 4;//获取4天之后的当前时间戳,一天为86400秒,这边是用毫秒,所以是86400000ms
pm.environment.set("gameHoldEndTime",gameHoldEndTime);