Timestamp generation in Postman - Build an Automation Script
/* Pre-request Script */ const timestamp = Date.now(); pm.variables.set('currentTimestamp', timestamp); /* Tests Script */ const timestamp = parseInt(pm.variables.get('currentTimestamp'), 10); pm.test('Timestamp is a number', () => { pm.expect(timestamp).to.be.a('number'); }); pm.test('Timestamp is recent', () => { const now = Date.now(); pm.expect(timestamp).to.be.within(now - 5000, now + 5000); });
In the Pre-request Script, we generate the current timestamp using Date.now() which returns milliseconds since 1970. We store it in a Postman variable currentTimestamp so it can be accessed later.
In the Tests tab, we retrieve the stored timestamp and convert it to a number. We then check two things: first, that it is a number type, and second, that it is within 5 seconds of the current time to ensure it is recent. This confirms the timestamp generation is working correctly.
We use pm.expect for assertions as recommended in Postman scripts. The code is kept simple and clear for easy understanding and maintenance.
Now add data-driven testing with 3 different time offsets (e.g., current time, 1 minute ago, 1 minute ahead) and verify timestamps accordingly