How to pass the current timestamp in Postman?
There are two methods to pass the current timestamp in Postman: either by using the Predefined variable {{$timestamp}} or by obtaining it through scripting and storing it in environment variables. Scripts can utilize the Date object to obtain timestamps.
In Postman, passing the current timestamp is a common task. You can utilize the Predefined {{$timestamp}}
variable to obtain the current timestamp and apply it to the request path to pass the timestamp. Additionally, you can also obtain the current timestamp through JavaScript scripting and store it in environment variables for repeated use in requests, as detailed below.
1.Obtaining the current timestamp using Predefined functions
Open a project in Postman, then select a request. Suppose there is a parameter 'timestamp' in the path that requires the timestamp. You can use the Predefined variable {{$timestamp}}
provided by Postman. After selecting it, send the request, and you will see the actual request path printed in the console with the current timestamp attached.
2.Obtaining the current timestamp through scripting
Apart from using Postman's Predefined variables, you can also obtain the timestamp through scripting. Once obtained, you can store it in environment variables or global variables, and finally reference this variable in the request path.In the script, you can use the Date object for obtaining the timestamp. Here's a reference example:
// Obtain the current timestamp (in milliseconds)
let timestamp = new Date().getTime();
console.log(timestamp);
The above code creates a Date object and then uses the getTime() method to obtain the timestamp of the object. The returned timestamp is the number of milliseconds since midnight (UTC) on January 1, 1970. If you need a timestamp in seconds, you can use Math.floor
or Math.round
:
// Obtain the current timestamp (in seconds)
var timestampInSeconds = Math.floor(new Date().getTime() / 1000);
console.log(timestampInSeconds);
Once the timestamp is obtained, you can store it in an environment variable, as shown in the script below:
let timestamp = new Date().getTime();
pm.environment.set('current_timestamp', timestamp);
If 'current_timestamp' field doesn't exist in your environment, Postman will automatically create it and assign the value.
Summary
There are two methods to pass the current timestamp in Postman: either by using the Predefined variable {{$timestamp}}
or by obtaining it through scripting and storing it in environment variables. Scripts can utilize the Date object to obtain timestamps.
Reference:
Learn more: