Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save JS Date.now() in PostgreSQL?

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.

like image 935
Alex Craft Avatar asked Mar 18 '17 15:03

Alex Craft


People also ask

How is date stored in PostgreSQL?

Postgres DATE data type Postgres uses the DATE data type for storing different dates in YYYY-MM-DD format. It uses 4 bytes for storing a date value in a column. You can design a Postgres table with a DATE column and use the keyword DEFAULT CURRENT_DATE to use the current system date as the default value in this column.

Can I use date now ()?

now() method is used to return the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC. Since now() is a static method of Date, it will always be used as Date.

What does date now () mean?

now() The static Date. now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.

What does date now () produce?

Date. now() returns the number of milliseconds since January 1, 1970.


2 Answers

Use the to_timestamp() postgres function:

`insert into times (time) values (to_timestamp(${Date.now()} / 1000.0))` 
like image 100
Udi Avatar answered Oct 12 '22 09:10

Udi


Or you can do something similar to this:

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

In your query builder:

... .update() .set({column_name: time}) 
like image 36
Anton Kornus Avatar answered Oct 12 '22 11:10

Anton Kornus