简体   繁体   中英

How do I compare a JSON date string to javascript string?

I'm trying to compare two time values, I am creating a new date variable in jS and then passing this down to Memberstack in JSON (this works). I am then calling the data when the page reloads and pulling the value back from Memberstack to compare the dates between the first load and second load.

Here is my code:

// Run timer. //
function runTimer() {
  
MemberStack.onReady.then(async function(member) {
  var metadata = await member.getMetaData() // <------ call the initial date value from Memberstack
  if (metadata.startDate != null) {
    var initiatedDate = metadata["startDate"]; // <------ the initial date value
    var referenceDate = currentDate; // <------ the second date value to compare to
    var calcDifference = referenceDate.getTime() - initiatedDate.getTime(); // <------ errors here
    var calcDifferenceD = calcDifference / (1000 * 3600 * 24); 
    alert(calcDifference);
    }
})

}
// End run timer. //

When I try to debug this in console I see the following:

安慰

When I run initiatedDate.getTime(); on line 83, I'm getting this error:

Uncaught (in promise) TypeError: initiatedDate.getTime is not a function

I need to make lines 81 and 82 match so that I can compare them, can anyone help me compare these two dates?

Right here is the answer to your question. Your initiatedDate is not an object, but a string, hence .getTime does not exist. So you should convert your string to a Date object.

This is how you can do it:

var initiatedDate = new Date(metadata['startDate'])

And then your initiatedDate will have the .getTime method and there's not going to be an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM