I want to do some time manipulation on these dates, specifically on the expiration date and subtract now() to determine the time remaining. I can extract the data from the JSON response via a Test, using:
However, I have no idea how to change that from a human-readable string to a date/time object.
I’m not sure if there is a Postman function to convert that string directly to data/time, or if I need to parse in some other way. I couldn’t seem to find much in the docs.
TIP: If you are only interested in the dates, use moment to format it as YYYYMMDD and parse it to an integer as this then becomes a number comparison at this point.
Example…
var moment = require('moment');
var today = parseInt(moment(new Date()).format("YYYYMMDD"));
By “object”, I meant data type that I could manipulate easily. Currently, expirationTime is a string, so getting into a date/time data type or converting it into something that could be manipulated was what I was after.
I tried:
const responseJson = pm.response.json();
const expirationTime = responseJson.expirationTime;
var moment = require('moment');
var expired = parseInt(moment(expirationTime));
console.log(expired);
Right, slightly different tack using modulo maths:
const responseJson = pm.response.json();
const expirationTime = responseJson.expirationTime;
// const timeFormat = "ddd, DD MMM YYYY hh:mm:ss"
var moment = require('moment');
var expiration = moment(expirationTime);
var today = moment();
console.log("Expiration date (Epoch time in milliseconds): " + expiration);
console.log("Todays date (Epoch time in milliseconds): " + today);
var diffSeconds = expiration.diff(today, 'seconds');
var numDays = Math.floor(diffSeconds / (24 * 3600));
var numHours = Math.floor((diffSeconds % (24 * 3600)) / 3600);
var numMinutes = Math.floor((diffSeconds % (3600) / 60));
var numSeconds = Math.floor(diffSeconds % 60 );
console.log("Time left: " + numDays + " Days, " + numHours + " Hours, " + numMinutes + " Minutes, " + numSeconds + " Seconds." );
Output:
Expiration date (Epoch time in milliseconds): 1691869015000
Todays date (Epoch time in milliseconds): 1688413437410
Time left: 39 Days, 23 Hours, 52 Minutes, 57 Seconds.
const responseJson = pm.response.json();
const expirationTime = new Date (responseJson.expirationTime;).getTime();
This will return the this time in Milliseconds (int).