Transform Non-Uniform Timestamps in Node?

Viewed 53

I'm using an API to query Google News and then store the results in Firestore.

Unfortunately the API returns non-uniform timestamp formats. Example: "1 Day Ago", "June 1, 2021", "4 Days Ago", "1 Week Ago", "1 Month Ago", etc.

I'd like to transform these dates to a uniform format before writing to Firestore so that I can easily sort them by date when calling to Firestore from the client.

I love to avoid writing custom conversion logic for each date format. Does anyone know of a library or off the shelf solution to make this simpler?

Here's my node code so far:

request(options, function(error, response) {
  if (error) throw new Error(error);
  const response = JSON.parse(response.body);
  const parsedResponse = Response["news_results"];
  for (let i=0; i<parsedResponse.length; i++) {
    // console.log(i);
    db.collection("articles").add(parsedResponse[i]);
  }
});
2 Answers

Can you provide more information about the API that you are using?

Looking at the docs on https://newsapi.org/s/google-news-api looks like there is a "publishedAt" property which can help you to achieve your goal.

You can use moment with simple parsing:

const now = moment()

const testData = {
  '1 Day ago': now.clone().subtract(1, 'day'),
  '11 Days ago': now.clone().subtract(11, 'days'),
  '1 Week ago': now.clone().subtract(1, 'week'),
  '2 Weeks ago': now.clone().subtract(2, 'weeks'),
  '1 Month ago': now.clone().subtract(1, 'month'),
  '3 Months ago': now.clone().subtract(3, 'months'),
}

console.log({ now, testData })

const dateFormat = 'YYYY-MM-DD'

const durationFromTime = (durationText, time) => {
  const parsedDuration = durationText.split(/\s/).slice(0, 2)
  return time.subtract(...parsedDuration)
}

Object.keys(testData).forEach((durationText) => {
  const parsedDate = durationFromTime(durationText, now.clone())
  const expectedDate = testData[durationText]
  console.log(`Check for '${durationText}':`, {
    parsedDate,
    expectedDate, 
    testPassed: parsedDate.unix() == expectedDate.unix(),
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Related