8

I have a simple t = Date.now; which goes to Postresql t_time column declared as timestamp with time zone via REST API. I got the error:date/time field value out of range.

I can't use the answer from this post as I don't write raw SQL but use ORM(Knex.Js). Calling db only to make the conversion looks like an overkill to me. Any other solution in js?

How come I can't find a convertor? Am I missing something?

Note: I just need date and time as hh:mm:ss, I don't need milliseconds.

SharpBCD
  • 547
  • 1
  • 7
  • 25

3 Answers3

19

Date.now() only provides the since EPOCH in milliseconds.

You need an ISO date time string. To achieve that, set t like this:

const t = new Date(Date.now()).toISOString();
console.log(t);
Randy Casburn
  • 13,840
  • 1
  • 16
  • 31
1

const getTIMESTAMPTZ = () => {
    const date = new Date();
    let offset = -date.getTimezoneOffset() / 60;
    const sign = (offset >= 0) ? '+' : '-';
    offset = Math.abs(offset);
    offset = (offset < 10) ? ('0' + offset) : offset;
    let TIMESTAMPTZ = date.toISOString();
    TIMESTAMPTZ = TIMESTAMPTZ.replace('T', ' ');
    TIMESTAMPTZ = TIMESTAMPTZ.replace('Z', `000${sign}${offset}`);
    return TIMESTAMPTZ;
};
console.log(' Example from PostgreSQL: ' + '2023-05-28 18:52:17.182883-07');
console.log('Output of getTIMESTAMPTZ: ' + getTIMESTAMPTZ());
McGrew
  • 812
  • 1
  • 9
  • 16
0

const t = Date.now().toString();
console.log(Date.now(), t);
const v = new Date(Number(t))
console.log(v);