Skip to content

Test & document date/time handling along with pitfalls #546

@brody4hire

Description

@brody4hire

From discussion in https://groups.google.com/forum/#!topic/phonegap/za7z51_fKRw I suspect date/time handling with JavaScript and SQLite databases can be a bit tricky. (I am not sure about IndexedDB but suspect similar issues with LocalStorage.) I can think of the following ways to store date/time in a SQLite database:

  • Integer (NUMERIC) value (note that the SQLite DATETIME typename has a NUMERIC type affinity)
  • String value

If someone just uses something like Date.now() in a SQL parameter list, its toString() function is called and the plugin would simply store the string value. (I am 99.9% sure that this would be the case for Web SQL as well.) I suspect that it is possible to use the valueOf() member function to get the numeric value.

It can also be tricky to figure out how to use date comparisons when selecting data.

From https://groups.google.com/d/msg/phonegap/za7z51_fKRw/gMCypOCwBQAJ:

There's actually two tricks to solving this.

First, if you declare your field as a datetime (which is nothing more than an integer) you will NEVER get this to work. Not under iOS 9.x, not under Android and not on Chrome 52.x (64-bit) on Windows 10.

What you have to do is store your date as a TEXT field and store your datetime as a string like this:

tx.executeSql("CREATE TABLE IF NOT EXISTS mytable (msg_id UNSIGNED INT PRIMARY KEY ASC, msg_when TEXT, msg_read INTEGER, title TEXT, msg_text TEXT)",

Next, you have to wrap your comparison in (parenthesis) so that sqlite treats it as a formula and does the math conversions for you... like this:

tx.executeSql(DELETE FROM mytable WHERE (msg_when <= datetime('now', '-4 days'))",

Notice the parenthesis before the (msg_when column and after the closing parenthesis on the datetime)) function.

(Note that he gave the JavaScript samples with the callback functions cut off.)

I personally think it should be possible and perhaps a little more efficient to use numeric "DATETIME" fields but may well be mistaken here. Unfortunately I cannot promise when I will have a chance to test this.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions