Saving a Date Gotcha

Unless, I’m mistaken, we need to be careful about how we save Dates to disk. Just saving the Date.TotalSeconds to disk and reading it back in seems to lose precision.

For example, this simplified code converts the total seconds to a string and back in a similar way that you might write to disk and read:

[code]dim now as new Date
dim seconds as double = now.TotalSeconds
dim secondsStr as String = str(seconds) // Store on disk as string

dim otherDate as new date
otherDate.TotalSeconds = val(secondsStr) // Read String from disk
MsgBox otherDate.longtime
[/code]
If you run it up, you’ll find it displays a time a few minutes off (and rounded.)

This code on the other hand always displays the correct time.

[code]dim now as new Date
dim seconds as double = now.TotalSeconds
dim secondsStr as String = format(seconds, “#”) // Store on disk as string but formatted

dim otherDate as new date
otherDate.TotalSeconds = val(secondsStr) // Read String from disk
MsgBox otherDate.longtime[/code]

Am I approaching this correctly?

SQLDateTime is good for saving dates to/from disk.

Like Tom said use SQLDateTime… but to answer your question…

STR and DOUBLE will sometimes return Scientific Notation…

for example… if you look at the result in your first piece of code… it returns “3.472707e+9”
not 347270714 so yeah it could be a few hundred seconds off that way.

Yes, SQLDateTime is probably better. I had gravitated towards total seconds as it was the “master” value behind dates.

Another solution is to pass your value to be written to disk as a variant instead of a string. That apparently keeps enough significant digits.
For example

3.472730e+9 // String
3.472730872e+9 // Variant acting as a string

Separately, if you really needed to store it in totalseconds value, pretty sure you could use the format function and specify enough digits in the format to ensure it doesn’t go to scientific notation.

BTW, which do you think is more widely supported outside of Xojo for external compatibility? SQLDate Time (YYYY-MM-DD HH:MM:SS) or XSD Time (2002-05-30T09:30:10+06:00)

a) avoid using VARIANTS whenever you can… tons of overhead
b) I’d say SQLDATE (it is what ORACLE uses)

I’d say SQLDateTime is more widely supported, but XSDDateTime is probably better due to the extra factor of timezones.

I think I’ll use SQLDateTime because it’s easier to parse. I’ll converting all times to GMT

Using Xojo is a huge overhead. What’s your point? :wink:

If you were using a binary format, I’d suggest using a double for total seconds and then a second double for GMT offset. 16 Bytes in total. I think you could probably store the GMT offset in a smaller number variant (like a single) but as Xojo uses a double I wasn’t sure about the precision.