skip to Main Content

I’m working with eBay api and trying to turn the endTime field which is in a dateTime format into a field that shows how much time is left in an auction, such as 5 minutes or 5 hours or 5 days.

In node, i’m making call to eBay api and mapping the endTime field into a variable, using the moment function.

It looks like this:

var moment = require("moment");
moment().format();

const cardsData = newData.map(card => ({
timeLeft: moment(
          card.listingInfo && card.listingInfo[0].endTime
        ).fromNow()

Every value in the loop is returning ‘a year ago’.

This is what the actual endTime field looks like

endTime: [
"2019-12-25T18:37:33.000Z"
],

where am i going wrong? does this date need to be formatted somehow before I can use moment?

2

Answers


  1. Chosen as BEST ANSWER

    So turns out adding a new Date wrapper gets this working. But i'm not exactly sure why. If anyone has any input, would be happy to hear. Thanks

     timeLeft: moment(
              new Date(card.listingInfo && card.listingInfo[0].endTime)
            ).fromNow()
    

  2. As @RobG pointed out, this is incorrect. Sorry.

    The expression you pass to moment(card.listingInfo && card.listingInfo[0].endTime) is a boolean expression, evaluating to true or false. Instead, I would filter newData where card.listingInfo is valid like this:

    newData = newData.filter(card => {
        return card.listingInfo && card.listingInfo[0];
    });
    

    Then for map you would do:

    newData.map(card => ({
        timeLeft: moment(card.listingInfo[0])
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search