Getting seconds from a date

Tagged: 

Viewing 3 reply threads
  • Author
    Posts
  • October 7, 2020 at 2:31 PM #42199

    Stefan de Graaf
    Participant

    Hey all,

    Hopefully a quick question: I’m trying something along the lines of this in a script field (based on a different date field):

    
    let dateField = record.getFieldValue('fld-060389f539934aa9b7163c7a8b7a4cd1');
    let delta = Math.abs(givenDate.getTime() - new Date().getTime()) / 1000;
    

    In JS, you can use getTime on a date object, but it seems you can’t do this with a Tap Forms date field’s value: TypeError: undefined is not an object (evaluating ‘givenDate.getTime’), line:(null)

    Is there a way to do this? Also tried creating a new Date() from the field’s value but that didn’t seem to work.

    Thank in advance!

    October 7, 2020 at 3:47 PM #42200

    Daniel Leu
    Participant

    This works for me:

    var date_created_id = 'fld-48f7c35e885c4d0db937b510c34d94f9';
    
    var dataField = record.getFieldValue(date_created_id);
    
    let delta = Math.abs(dataField.getTime() - new Date().getTime()) / 1000;
    console.log(delta)

    I noticed that in your example you assign something to dateField but then later you use givenDate.

    October 7, 2020 at 4:37 PM #42201

    Stefan de Graaf
    Participant

    Thanks for the help! Ah that was a copy-paste mistake indeed (older version of the script). I tried it with your version but keep getting the same “TypeError: undefined is not an object (evaluating ‘dataField.getTime’), line:(null)” error. And the date field is a regular date field (only the name has been changed) and has a date set. Will have to play around some more tomorrow.

    October 7, 2020 at 5:51 PM #42204

    Sam Moffatt
    Participant

    The undefined is not an object error would generally indicate the field is empty or hasn’t been set yet when referring to dataField there. When a field value for a record isn’t set, getFieldValue will return an undefined value.

    To handle that situation, you can wrap it in an if statement to see if it’s set to a value before continuing:

    var date_created_id = 'fld-48f7c35e885c4d0db937b510c34d94f9';
    
    var dataField = record.getFieldValue(date_created_id);
    
    if (dataField) {
        let delta = Math.abs(dataField.getTime() - new Date().getTime()) / 1000;
        console.log(delta)
    } else {
        console.log("Date not set");
    }
    
Viewing 3 reply threads

You must be logged in to reply to this topic.