Search code examples
javascriptnode.jsunixtimestampunix-timestamp

interpreting unix time in the context of hours


I am new to Javascript development and I recently came across the use case of UNIX time. I was wondering how I could use it for my purpose. My desired outcome is simple: get unix timestamp values from database, compare them to the current timestamp, if the difference between the current timestamp and a timestamp value from the database is less than 72 hours append the value to a new array.

Here is my current code:

  return new Promise((resolve, reject) => {
    var sql = `SELECT id, s3_location, s3_expiration FROM sounds`;
    con.query(sql, function (err, result) {
      if (err) throw err;

      for (let i = 0; i < result.length; i++) {
        console.log(Date.now())
        console.log(result[i].s3_expiration)
      }

      resolve(result);
    });
  });

s3_expiration returns the timestamp from the database and date.now is the present one. Here is some sample output from the logs:

1628174289
1628360565071
1628174294
1628360565071
1628176443
1628360565071
1628176454
1628360565071
1628176526
1628360565071
1628176561
1628360565071
1628176568
1628360565071
1628176578
1628360565071
1628881107
1628360565071
1628881164
1628360565071
1628281251
1628360565071
1628281258
1628360565071
1628281755

The one with the more digits is the value from date.now() while the shorter one is from the database. Let me know how I can accomplish my desired outcome. Any help would be much appreciated!


Solution

  • Date.now() is returning milliseconds since Jan 1st 1970.
    And the shorter one looks to be the same thing, but in seconds.

    So here is how If would make the comparision:

    return new Promise((resolve, reject) => {
      var sql = `SELECT id, s3_location, s3_expiration FROM sounds`;
      con.query(sql, function (err, result) {
        if (err) throw err;
    
        let seventyTwoHours = 72 * 60 * 60;
        let nowInSec = parseInt(Date.now() / 1000);
    
        for (let i = 0; i < result.length; i++) {
          if (result[i].s3_expiration > nowInSec - seventyTwoHours) {
            console.log("The timestamp is less than 72 hours old");
          }
    
          console.log(Date.now());
          console.log(result[i].s3_expiration);
        }
    
        resolve(result);
      });
    });