1

I have saved a datetime value created by Luxon into a postgres database column, of type TIMESTAMP(3). I want to then use that value, convert it into other time zones, etc. However, I can't seem to figure out how to "use" it.

I created the object using the following

const { DateTime } = require("luxon");
const myDate = DateTime.now().toUTC().toISO()

I then inserted it into a postgres database, into a column of type TIMESTAMP(3).

I extract it out of the database using a query. When I log it, it says its value is:

console.log(extracted_date);                      //=> "2021-12-27T09:57:16.184Z"
console.log(typeof extracted_date);               //=> object

// The following return "unparsable" or undefined objects
DateTime.fromISO(extracted_date);
DateTime.fromObject(extracted_date);

I can find plenty of tutorials about how to insert dates into sql, but nothing on how to take that date object and actually do something with it. I want to, for instance, convert its time zone.

1 Answers1

1

To use that date object you can initiate a new Date, like so:

console.log(extracted_date);  //=> "2021-12-27T09:57:16.184Z"
const javascriptDate = new Date(extracted_date);

Than you can use it directly or with the luxon library.

console.log(javascriptDate.toGMTString()); // => "Mon, 27 Dec 2021 09:57:16 GMT"
console.log(javascriptDate.toISOString()); // => "2021-12-27T09:57:16.184Z"
console.log(javascriptDate.valueOf()); // => 1640599036184

This object core is actually, a value that represents milliseconds since 1 January 1970 UTC, and added to that are time and string parsing functions, generally speaking.


More Info

In some systems dates are store in the database as the value - date.valueOf() - which make it clearer (for a developer) you have to manipulate it, and perhaps reduce problems of showing the wrong timestamp to users. In the other hand - you lose the readability. Another opion is using only UTC time in your system and convert the timestamp on client side or before presenting the data. The use of UTC will make sure all of your dates will have same language'.

If you want to read more about timestamp, here are some references:

UTC vs ISO format for time

What is the "right" JSON date format?

NBekelman
  • 13
  • 5