50

I tried to use PostgreSQL timestamp datatype, but it throws an error

ERROR:  date/time field value out of range: "1489849402536"

The schema

create table times (
  time   timestamp    not null,
);

JS code

`insert into times(time) values (${Date.now()})`

P.S. another option is to use bigint but it seems like an overkill.

Alex Craft
  • 13,598
  • 11
  • 69
  • 133

3 Answers3

62

Use the to_timestamp() postgres function:

`insert into times (time) values (to_timestamp(${Date.now()} / 1000.0))`
Udi
  • 29,222
  • 9
  • 96
  • 129
  • 12
    By way of explanation for this answer, JavaScript `Date.now()` returns the number of _milliseconds_ since the Unix Epoch (1 Jan 1970). PostgreSQL `to_timestamp(…)` converts a single argument, interpreted as the number of _seconds_ since the Unix Epoch into a PosgtreSQL timestamp. At some point, the JavaScript value needs to be divided by 1000. You could also write `to_timestamp(${Date.now()/1000})`. – Manngo Mar 19 '17 at 09:36
  • Thanks didn't knew that PostgreSQL uses seconds instead of milliseconds, so sadly there will be a data loss... – Alex Craft Mar 19 '17 at 10:49
  • 2
    To keep milliseconds, use `/ 1000.0` instead. I have fixed my answer above. – Udi Mar 19 '17 at 11:07
  • 3
    Why is the ${ } syntax needed? – Edward Oct 04 '17 at 17:50
  • It is string injection. You can write 'INSERT INTO times (time) VALUES (to_timestamp(' + Date.now() /1000.0 + '))' too. @Edward – Capan Oct 08 '19 at 15:25
  • Thanks Udi and Manngo. I been figuring out this for hours. – Rafael Parungao Feb 10 '21 at 11:04
28

Or you can do something similar to this:

const time = new Date().toISOString();

In your query builder:

...
.update()
.set({column_name: time})
Anton Kornus
  • 547
  • 5
  • 6
3

Just in case you are using Sequelize, you can use: sequelize.literal('CURRENT_TIMESTAMP'). Example:

await PurchaseModel.update( {purchase_date : sequelize.literal('CURRENT_TIMESTAMP') }, { where: {id: purchaseId} } );
Arthur Mastropietro
  • 673
  • 1
  • 7
  • 22