skip to Main Content

I have the following query

let mercadoLivreCredencialDB =  await mercadoLivreCredencial.findOne({
  where: { id : 1 }
});


if(mercadoLivreCredencialDB.data < someJavascriptWay){// I need to calculate if the data column has a datetime that is less than six hours based on the current time
}

I am using node with Javascript. Any help would be welcome. My data column is time stamp without time zone ex: "2023-04-29 23:45:17.833445"

2

Answers


  1. Let’s assume the returned type can be one of the following: Date object, string (ISO compatible) or number (UNIX timestamp), we can then convert all of them to UNIX timestamp in milliseconds for comparison:

    function isWithinLast6Hours(dateOrStringOrNumber) {
      let timestampInMs = 0;
      if (dateOrStringOrNumber instanceof Date) {
        // Just convert to milliseconds
        timestampInMs = dateOrStringOrNumber.valueOf();
      } else if (typeof dateOrStringOrNumber === 'number') {
        // UNIX timestamp is in seconds
        timestampInMs = dateOrStringOrNumber * 1000;
      } else {
        // Try to parse
        timestampInMs = new Date(dateOrStringOrNumber).valueOf();
      }
    
      const sixHoursAgo = new Date();
      const sixHoursAgo = sixHoursAgo.setHours(sixHoursAgo.getHours() - 6);
      return (timestampInMs >= sixHoursAgo);
    }
    

    You can then use the following:

    isWithinLast6Hours(mercadoLivreCredencialDB.data);
    
    Login or Signup to reply.
  2. Saw the other answer, but it seems unneccesarily complicated – Dates are automatically converted to ms when doing calculations and comparisons in JavaScript, so there should not be any need for valueOf, getTime() or any similar attempt to manually convert them…

    Assuming the timestamp is UTC/GMT for your date, and your date (in the format you specified) is x, this is all you need:

    let isOlderThan6h = Date.now() - 6 * 60 * 60 * 1000 > new Date(x + 'Z');
    

    If the timestamp is in local time zone, rather than UTC, then omit + ‘Z’:

    let isOlderThan6h = Date.now() - 6 * 60 * 60 * 1000 > new Date(x);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search