Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postman random start and end dates

Tags:

postman

How can I generate dynamic random start and end dates for a post request in the YYYY/MM/DD format? This is what I tried in the pre-request script but it does not work

    const moment = require('moment');
    pm.globals.set("start", moment().format(("YYYY/MM/DD")));
like image 734
gswervo Avatar asked Dec 14 '25 22:12

gswervo


1 Answers

You can solve this with a mix of Postman Dynamic Variables and momemt for formatting. These variables get generated at execution time (when you send a request) so you have different values for each request. You can use the following variables:

  • $randomDateFuture
  • $randomDatePast
  • $randomDateRecent

You can use them directly as you would use a collection or global variable in query params, etc. If you want to use these variables on scripts then you have to use it like this:

const startDate = pm.variables.replaceIn('{{$randomDatePast}}')

So for your example in concrete I've written a request you can see here (check pre-request script). Also posting the code here for future perservation:

const moment = require('moment')

// Generate a past and future date using dynamic postman variables 
let futureDate = pm.variables.replaceIn('{{$randomDateFuture}}'),
    pastDate = pm.variables.replaceIn('{{$randomDatePast}}')

// Use moment to output the right format
futureDate = moment(futureDate).format(("YYYY/MM/DD"))
pastDate = moment(pastDate).format(("YYYY/MM/DD"))

console.log(futureDate)
console.log(pastDate)

The output looks like this:

enter image description here

like image 132
bitoiu Avatar answered Dec 16 '25 22:12

bitoiu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!