sqlitedatecore-datatimestampnsdate

How do I convert a CoreData date interval to a SQLite date?


Something went wrong with my app's data! For debugging purposes only, I downloaded the app's container so I could take a look inside it's CoreData .db file.

I'm using a SQLite client to query it. I've found that in it, dates (NSDates) are stored as if from the result of dateToStore.timeIntervalSinceReferenceDate, which is the number of seconds since the start of 2001.

SQLite has this nice function which will convert a UNIX timestamp, but those start at the end of 1970:

SELECT datetime(ZDATECOLUMN, 'unixepoch') FROM ZTABLENAME

So today's date, 2016-05-11, would have a CoreData timestamp something like 484676143.607, but a UNIX timestamp like 1462997743.607. When using the above SQL for my data, today's date would appear as 1985-05-11. How do I use SQL to get back these CoreData timestamps as human-readable dates?


Solution

  • This question is ancient, but I was trying to do it today. You can use datetime(), you just need to add 978307200 to the coredata timestamp. Coredata timestamps are seconds since 2001-01-01. 978307200 is the difference in seconds between unix epoch and coredata epoch. So, in the form of the original question, you could do this:

    SELECT datetime(ZDATECOLUMN + 978307200, 'unixepoch') FROM ZTABLENAME