简体   繁体   中英

Select Sqlite date values in ISO 8601 format

I'm using Knex.js to select records from a SQLite database. I then wish to return the records as JSON as part of a web api. When selecting dates form Sqlite they are formatted like 2018-01-01 00:00:00.000

I would like them to be formatted like JavaScript's date toJSON() function: 1975-08-19T23:15:30.000Z

Is there a way to have the database format the date fields like this when querying it?

So I was hoping there's a way in a connection string, or Knex, etc. to tell Sqlite how to format the dates.

Short answer: Sorry, there's not.

SQLite stores your ISO8601 dates as strings and doesn't have built-in data types to vary that.

From SQLite Documentation :

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").

REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 BC according to the proleptic Gregorian calendar.

INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.

Possible Workaround #1 - in the database: You can probably use the strftime() noted by @sbooth in a CREATE TRIGGER BEFORE ... to override the default storage string format. Docs link (Sorry, I haven't personally done this though.)

Possible Workaround #2 - in the JS code: Use javascript (like you mentioned: .toJSON() ) to pre-format the date strings in another way for storage. I use something like:

var createDate = (new Date()).toISOString();

... to format my dates for storage in the code, which has the format you are looking for: '2018-01-28T02:39:53.226Z' .

Also, a possible gotcha to watch for: When you SELECT an ISO8601 string date 'type' from the SQLite DB via Knex, it will return as a string type, not a Date() type.

Hope this is helpful. Gary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM