0

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:

Console

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?

van
  • 158
  • 1
  • 2
  • 12
  • 2
    because initialDate is a string, you need to convert it to Date object, i prefer moment.js when dealing with dates – Nonik Aug 06 '20 at 19:53
  • @Nonik can I use: `var obj = JSON.parse('{""}');` for this? if so what is the correct syntax? – van Aug 06 '20 at 19:55
  • What do you mean by JSON Date String? I think reference is a Date object. You need to convert the other string to a date object as well – iamkhush Aug 06 '20 at 19:56
  • try new Date(initiatedDate); but again, i prefer moment.js when dealing with dates – Nonik Aug 06 '20 at 19:57
  • Does this answer your question? [Converting a string to a date in JavaScript](https://stackoverflow.com/questions/5619202/converting-a-string-to-a-date-in-javascript) – imvain2 Aug 06 '20 at 19:58

1 Answers1

2

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.