javascriptpostmanpostman-pre-request-script

How to generate future date and time for postman request


{
    "name": "IronMan",
    "phone_number": "555555555",
    "number_of_guest": 10,
    "tables": [
        2
    ],
    "reservation_start_at": "2020-10-15T10:00:00.861873Z",
    "reservation_end": "2020-10-15T11:00:00.861873Z"
}

I am stuck at step where I need to generate future date and time with time zone to send a postman request. The request is about a reservation feature.

On the request body,a key-value is,

"reservation_start_at": "2020-10-15T10:00:00.861873Z"

My question is, how do I generate future date and time for each request?

Thanks in advance .


Solution

  • You can use the following in postman's pre-request script:

    var moment = require('moment');
    
    const yearsInTheFuture = 1;
    const monthsInTheFuture = 2;
    const daysInTheFuture = 3;
    const hours = 12;
    const minutes = 34;
    const seconds = 56;
    const milliseconds = 789;
    const durationInDays = 7;
    
    const reservation_start_at = moment()
        .add(yearsInTheFuture, 'years')
        .add(monthsInTheFuture, 'months')
        .add(daysInTheFuture, 'days')
        .hours(hours)
        .minutes(minutes)
        .seconds(seconds)
        .millisecond(milliseconds);
    
    reservation_end = moment()
        .add(yearsInTheFuture, 'years')
        .add(monthsInTheFuture, 'months')
        .add(daysInTheFuture + durationInDays, 'days')
        .hours(hours)
        .minutes(minutes)
        .seconds(seconds)
        .millisecond(milliseconds);
    
    console.log("reservation_start_at: " + reservation_start_at);
    console.log("reservation_end: " + reservation_end);
    
    pm.environment.set("reservation_start_at ", reservation_start_at);
    pm.environment.set("reservation_end", reservation_end);
    

    It will set the environment variables reservation_start_at and reservation_end, which you then can access in the request body:

    {
       "name":"IronMan",
       "phone_number":"555555555",
       "number_of_guest":10,
       "tables":[
          2
       ],
       "reservation_start_at":"{{reservation_start_at}}",
       "reservation_end":"{{reservation_end}}"
    }