How do I work with twilio date parameter?

edited September 5 in Functions

Hey all. I had a quick question about twilio I'm hoping to get some insight on. I'm building an autopilot bot that requires age authentication. What I had in mind was gathering the date from user in a twilio date object, capturing the current date in a function, and then running the logic to write the result to a database. The question I have is, what's the easiest way to extract the year, month, and day from within the twilio date object. Is there a simple way like with javascripts Date.prototype.getDay(), etc? Thanks for any insight

Best Answer

  • pnash
    pnash mod
    Accepted Answer

    I dropped you an answer on Stack Overflow, but this question seems slightly different. If you follow my advice from Stack Overflow and throw the data over to a Twilio Function then you have all of JavaScript at hand to parse the date.

    You mention it's a string of format "2002-04-24". You can parse this into year, month and day components like:

    const dateString = "2002-04-24";
    const [year, month, day] = dateString.split("-").map(part => parseInt(part, 10));
    console.log(year, month, day);
    // => 2002, 4, 24

    The format "2002-04-24" is also the first part of an ISO 8601 date, so parsing with the Date constructor should work:

    const dateString = "2002-04-24";
    const date = new Date(dateString);
    console.log(date.getFullYear(), date.getMonth(), date.getDate());
    // => 2002, 3, 24
    // Watch out for zero indexed months!

    Let me know if this helps.


  • developwithdata
    edited September 8

    Hey Pnash, thanks for the reply and sorry for my late reply. I have a tentative solution using,

    let birth_year = Number(birthday.substring(0,4));
    let birth_month = Number(birthday.substring(5,7));
    let birth_day = Number(birthday.substring(8, 10));

    Do you foresee any bottlenecks with solution I'm using, or anything I'm over-looking? I'll revisit your suggestion for this if I come across any issues with this. Also, just saw your reply on stackoverflow. It's an honour to have "The Twilio Evangelist" reply to my post.

    I've received a lot of info from your replies before having to ask a question myself.

    So thank you for doing the community such a wonderful service.

  • Your solution absolutely works too. I tend not to work with substrings to parse things out of a string in case the format of the string changes, substring is very rigid and will always pick those specific characters. In this case the format of a date is not going to change, so you should be safe.

    I'm very glad to hear that other answers on Stack Overflow have helped you too! Though I am not the only Twilio evangelist, there are plenty of us all over the world and internet ready and waiting to help out.