Save Date.now() to postgres

Asked

Viewed 222 times

0

Hello, I would like to know what kind of data I use in the time column of my table, which will store the Date.now() from Javascript, it returns an integer like this 1591181717431. I thought to use the big int, someone has a better idea?

  • 1

    And if instead of taking the Date.now() you catch the new Date() and store as Timestamp in the bank?

  • 1

    I saw a people talking that it is very good to study timestamp and UTC, I think I will do what Denis said. Vlw. Grateful.

  • By chance there is some particularity in its application that makes the Date.now() of Javascript other than now() Postgresql? If you don’t have to put as DEFAULT clause in the field of your table.

2 answers

1


This whole number is the amount of milliseconds that have passed since the date of 01/01/1970 at 00:00:00 to date. Formally known as Unix age.

Postgres is capable of converting an integer representing the Unix Age in seconds to the type TIMESTAMP through the function to_timestamp(), look at you:

CREATE TABLE tb_foobar
(
    id INTEGER,
    datahora TIMESTAMP
);


INSERT INTO tb_foobar (id, datahora) VALUES (1, to_timestamp(1591181717431 / 1000));
INSERT INTO tb_foobar (id, datahora) VALUES (2, to_timestamp(1591182735732 / 1000));
INSERT INTO tb_foobar (id, datahora) VALUES (3, to_timestamp(1581182718337 / 1000));

Consulting Table:

SELECT id, datahora FROM tb_foobar;

Exit:

| id |             datahora |
|----|----------------------|
|  1 | 2020-06-03T10:55:17Z |
|  2 | 2020-06-03T11:12:15Z |
|  3 | 2020-02-08T17:25:18Z |

See working on Sqlfiddle

1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.