Test to check if timestamp is from today or within last 3 minutes?

Hello,

I’m not sure if I am just searching for the wrong things, but I can’t seem to find any test examples like this.

I’m looking to create a test that validates of a json response value (timestamp) is from today, or even better if it was within the last 3 minutes

Example Timestamp: 2019-09-16T17:51:17Z

I’ve found a few java examples that compare 2 times, but I cant seem to figure out how to translate them to work as a test.

My guess is that i need to convert the timestamp from a string to something that can be compared against a date?

Any advice would be appreciated!

Think i figured it out using moment:

let dateNow = moment().format(“DD/MM/YYYY hh:mm:ss.SS”)
dateNow = moment().subtract(5,“minutes”).toDate()
let dateDiff = moment(Data.organizations[0].created_at).isAfter(dateNow)

pm.test("Created within the last 5 minutes: " , () => {
pm.expect(dateDiff).to.be.true
})

1 Like

Hey,

You could try taking a look at Moment.js | Docs this module is included with Postman and is awesome when dealing with times and dates in JS.

I create a really horrible basic check that might test that but I’m 100% sure there is a cleaner way of doing this within a test. :slight_smile:

In order to use moment, you would need to add the require() statement but apart from that you’re good to go. I don’t actually know where in your response, that the timestamp key is so I’ve made a massive assumption and guessed it’s at the top level but that might not be the case.

const moment = require("moment")

let timestamp = moment(pm.response.json().data.timestamp).format("YYYY-MM-DD")
let isToday   = moment().format("YYYY-MM-DD")

pm.test("Check date is Today", function () {
    pm.expect(moment(timestamp).isSame(isToday), "Dates do not match").to.be.true;
});

The test is using the isSame() function to do well…just that. It’s getting the timestamp from the response and checking that against todays (or the day when you run it) date. I’ve formatted the value so it’s just the date getting checked rather than the time.

You could change this and use some of the other functions of moment, to cut the time range down to 3 minutes, this is just something I created without thinking about it for too long so I can imagine it might be wrong.