Optimal way to store datetime values in SQLite database (Delphi) - delphi

I will be storing datetime values in an SQLite database (using Delphi and the DISqlite library). The nature of the db is such that it will never need to be transferred between computers or systems, so interoperability is not a constraint. My focus instead is on reading speed. The datetime field will be indexed and I will be searching on it a lot, as well as reading in thousands of datetime values in sequence.
Since SQLite does not have an explicit data type for datetime values, there are several options:
use REAL data type and store Delphi's TDateTime values directly: fastest, no conversion from string on loading; impossible to debug dates using a db manager such as SQLiteSpy, since dates will not be human-readable. Cannot use SQLite date functions (?)
use a simple string format, e.g. YYYYMMDDHHNNSS: conversion is required but relatively easy on the CPU (no need to scan for separators), data is human-readable. Still cannot use SQLite date functions.
do something else. What's the recommended thing to do?
I have read http://www.sqlite.org/lang_datefunc.html but there's no mention of what data type to use, and, not being formally schooled in programming, I don't quite grok the focus on Julian dates. Why the additional conversion? I will be reading in these values a lot, so any additional conversions between strings and TDateTime adds a significant cost.

You could use one of the SQLite supported string formats, eg. YYYY-MM-DD HH:MM:SS.SSS.
It would be just as easy as YYYYMMDDHHNNSS - you still wouldn't need to scan for separators, since all the numbers are fixed length - and you would get SQLite date function support.
If you need SQLite date function support, I would go with that method.
If not, I'd recommend using REAL values. You can still compare them to each other (higher numbers are later in time), and consider date and time separately (before and after the decimal point respectively) without converting to TDateTime.

One compromise would be to stick with REAL values, but store them as julian dates by using Delphi's DateTimeToJulianDate. That way they remain fast for reading, there's little performance lost in the converation, and they're still in a format that makes sense outside of Delphi.

For this I usually use an Integer data type and store the Unix timestamp value alike (eq # seconds since 1-1-2000 for example). Calculating this t/from a TDateTime is equal to multiplying/diving with/by 86400 and adding a constant for the 'since'.
If you need more precision You could use the DateTime as a FILETIME (eg int64) which has 100 ns increments. There are conversion routines in SysUtils for that and your timestamp is stored in UTC.

If your concern is only human readable format at database level, you can store two separate fields, for example:
DELPHI_DATE REAL (DOUBLE, if possible, but I don't know SQLite), Indexed. All your programmatic queries and comparisons should use this field.
HUMAN_READABLE_DATE Varchar(23) with format 'YYYY-MM-DD HH:MM:SS.SSS'. Maybe indexed (if really necessary). Majority of human input queries should include this field and you can use (as said by others) SQLite date functions.
It has some drawbacks:
Space consumption at database and network traffic grows,
insert operations will take a bit more because necessary conversion,
no automatic synch between values if updated outside your program
If it is suitable for your particular needs, is up to you.

I don't know if this answer is applicable to the DISqlite library but...
Below is some code that illustrates what works for me using both Delphi 2010 and Tim Anderson's SQLite3 wrapper.
SQL to create field:
sSQL := 'CREATE TABLE [someTable] (' +
' [somefield1] VARCHAR(12),' +
' [somefield2] VARCHAR(12),' +
' [myDateTime] DATETIME );';
SQL to populate field:
sSQL := 'INSERT INTO someTable(somefield1, somefield2, myDateTime)' +
' VALUES ( "baloney1", "baloney2","' + FloatToStr(Now) + '");';
Example of retrieving data from field:
var
sDBFilePathString: string;
sl3tbl: TSqliteTable;
fsldb : TSQLiteDatabase;
FromdbDTField : TDateTime;
begin
...
...
fsldb := TSQLiteDatabase.Create(sDBFilePathString);
sl3tbl := fsldb.GetTable('SELECT * FROM someTable');
FromdbDateTime := StrToFloat(sl3tbl.FieldAsString(sl3tbl.FieldIndex['myDateTime']));
Showmessage('DT: ' + DateTimeToStr(FromdbDTField));
end;
Result:
**DT: 10/10/2013 1:09:53 AM**
Like I mentioned on the first line - I don't know if this will work with the DISqlite library but if it does its a pretty clean way of handling things.
I leave it to you to make things prettier or more elegant.

Related

Does neo4j supports property data format?

Does neo4j natively support data format for node properties? like for example url links (clickable), numbers (integer, float..), date (YYYY/MM/DD).
Or we need to programmatically convert property string to whatever format we need?
Property values in Neo4j could be either Java primitive types (float, double, int, boolean, byte,... ), Strings or array of both. Date objects as property values are not supported.
There are two ways to deal with days:
Store the date as msec since epoc, aka new Date().getTime() (in java)
pro: you can do calculations
pro: less memory/disc consumption as it's stored as a long
con: when just looking at the node, it's hard to infer the date without calculation
Store the date as a string using e.g. SimpleDateFormatter
pro: human readable
con: calculations are hard
Personally I tend to prefer the first one.
In case you need to store time + timezone, you can have two properties. One for the date in msecs based on UTC, another one for the timezone.

How to change the system shortdatetime format using delphi xe3

I am going to try and make the question as simple as possible.
How do i either convert the system date to a format i would like, and still keep it a date and not a string.
Or how do i get the system's date format, to adjust my dates accordingly.
When i call
FormatShortdateTime('d/M/yyyy',Date);
I get the correct date as string, but cannot convert it back to a Tdate and use it, then it clashes with the system date settings.
If i can get the system shortdate format the problem would be solved.
Update
The answer below refers to the original question that you asked. You've edited the question multiple times now to ask different questions. You really should not do that and it is a sign that you should spend more time understanding the problem before asking questions.
Even so, the final part of the answer, probably still contains the advice that you need. Namely to stop using conversion functions that rely on the global FormatSettings variable, and always use conversion functions that are passed format settings as a parameter.
The date values in your database are not stored in the format that you expect. This program:
{$APPTYPE CONSOLE}
uses
System.SysUtils;
var
fs: TFormatSettings;
begin
fs := TFormatSettings.Create;
fs.ShortDateFormat := 'd/M/yyyy';
Writeln(DateToStr(StrToDate('18/2/2014', fs)));
end.
produces the following output on my machine:
18/02/2014
I guess on your machine it would produce a different output because your short date format is different from mine. But the point is that the call to StrToDate succeeds.
Clearly the values stored in your database are not in the form you claim. Because you claim that the above code would lead to a date conversion error in the call to StrToDate.
Let's step back and look at the initial part of your question:
I would like to know how to convert dates without having the system date influence the software.
The code in the answer above gives you an example of how to do that. Modern versions of Delphi overload the date and time conversion functions. There are overloads that accept TFormatSettings parameters, and overloads without such a parameter. The TFormatSettings parameter is used to control the format used for the conversion. The overloads that do not receive such a parameter use the global FormatSettings instance declared in the SysUtils unit.
What you should do to avoid having the system settings influence your conversions is to only use conversion functions that accept a format settings parameter.
On the other hand, if you want the system settings to influence your conversions, then feel free to call the overloads that use the global format settings variable.
My code above illustrates both. The conversion from string to date requires a fixed format, not varying with local system settings. The conversion from date to string is designed to show a date using the prevailing local system settings.
I would advice creating own TFormatSettings variable
older delphi versions
var
fs: TFormatSettings;
begin
fs := TFormatSettings.Create;
GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, fs);
end.
This will create your own formatSettings (filled with system format) so you won't alter the default one.
Now what's important is that '/' in shortDateFormat will be replaced by dateSeparator so if you do this
fs.ShortDateFormat:='M/d/yyyy';
fs.dateSeparator:='?';
your input should be like this
strtodate('12?30?1899', fs);
or if other way around you will end up with string: '12?30?1899';
I think that your problems originate from that you don't ask what dateSeparator is used. That would lead to problems if what program expects is '30-12-1899' but he gets '30/12/1899' from you.

Overriding the system Date Format

In my application I am reading from one database and writing to a second. The app is quick and dirty so I am reading / writing using AsString on both the FieldByName and ParamByName of the queries.
This works for all my use cases apart from where the data type is Date or DateTime
As far as I can tell FieldByName.AsString uses the system ShortDateTime format to return dates as (in my case) dd/mm/yyyy. The database expects the date to be written in as yyyy-mm-dd
According to Delphi Basics I should be able to set ShortDateFormat to what I need, but it appears that in XE5 this is no longer the case (correct?)
Further digging on here returns these two questions that use TFormatSettings to override the local settings. However, both of these use the resulting FormatSettings in StrToDate and FormatDateTime directly.
So two questions
1) Can I tell my application to override the System ShortDateFormat?
2) If so, How (I have a Plan B if not)?
The use of a global variable for the date and time formats was a mistake committed long ago by the original RTL designers. Functions that rely on the global format settings, like the single parameter StrToDate are retained for backwards compatibility, but you should not be using them.
For conversions between date/time and string you should:
Initialise a TFormatSettings instance with your date format.
Call the two parameter StrToDate, passing your TFormatSettings to convert from a string to a date.
Call FormatDateTime overload that accepts a TFormatSettings when converting in the other direction.
Now, to the main thrust of your question. You should not be using strings at all for your dates and times in the scenario you describe. Use AsDateTime rather than AsString. If you happen to have a database column that does store a date/time as a string, then you'll should use the TFormatSettings based conversion functions to work around that design fault.
If you are absolutely dead set on doing this all with strings, and I cannot persuade you otherwise, then you need to use FormatSettings.ShortDateFormat from SysUtils to control your short date formatting.

Converting Date Format in Advantage SQL

I have a simple problem in Advantage Database SQL.
I have dates in the format M/D/YYYY and want to convert them MM/DD/YYYY. Normally in SQL Server I would just use a convert(varchar(20), field, 101) but this does not work in Advantage.
What is the format for doing so?
I don't believe there is a simple conversion function like that available. To convert it directly in SQL would probably turn into a fairly messy statement (I think it would require a combination of CONVERT, YEAR, DAY, and MONTH scalars).
If the goal, though, is to force the display of date values in a specific format in the client application, then one possibility might be to specify the date format at connection time. How you do that depends on the client being used. If, for example, you are using a connection string, then you may be able to specify the date format as follows.
Data Source=\\server\share\yourdatapath;...;DateFormat=MM/DD/YYYY;

Using decimal data type to work with monetary values with db2 and delphi 2010

I'm using delphi 2010 with db2 9.7 Express-C and I have a database that has several fields of decimal type to work with monetary values. Now I see that there are some problems using it, like the 9.20 value displays the value 9.19999980926514 in my front-end. I need to change all the fields in my database to DECFLOAT or is there a function, property in tfield or other alternative to solve it ?
Thanks.
Davis
working directly with monetary decimals is almost always a problem. due to different conversions made from the database to your front-end application, it is possible to lose or to gain(this applies to most of the financial systems also - see bankers rounding).
I suggest you to use the RoundTo function before making operations/display/etc. A very good article about rounding http://docwiki.embarcadero.com/RADStudio/XE2/en/Floating-Point_Rounding_Issues
Another suggestion will be using of the Currency type. Here is a question on SO with good explanation about this type How to avoid rounding problems when comparing currency values in Delphi?

Resources