Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert node Date() into postgresql timestamp column?

I want to update several records with the same time, and I can't figure out how to do it.

I've tried various combos with pg-promise and moment and node alone:

myTs = Date();
myTs = moment(new Date()).format("YYYY-MM-DD HH:mm:ss"); 

with sql:

UPDATE mytable set ts = $1;
UPDATE mytable set ts = $1::timestamp;

errors:

 time zone "gmt-0800" not recognized
like image 741
Coco Avatar asked Jul 02 '26 19:07

Coco


1 Answers

It is better to store timestamps in a database in UTC format without time zones.

Suppose there is a table (PostgreSQL):

create table test_time (utc_time timestamp);

To insert the current UTC timestamp:

const res = await db.query({
  text: "insert into test_time (utc_time) values ($1) returning *",
  values: [new Date(new Date().toISOString())],
});

Or you can insert the current Date with a time zone depending on your runtime:

const res = await db.query({
  text: "insert into test (date) values ($1) returning *",
  values: [new Date()],
});
like image 107
Albina Avatar answered Jul 04 '26 17:07

Albina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!