问题描述
我使用核心数据来做到这一点:
I used core data to do this:
NSManagedObjectContext *m = [self managedObjectContext];
Foo *f = (Foo *)[NSEntityDescription insertNewObjectForEntityForName:@"Foo"
inManagedObjectContext:m];
f.created_at = [NSDate date];
[m insertObject:f];
NSError *error;
[m save:&error];
其中 created_at 字段在 xcdatamodel 中定义为类型Date".
Where the created_at field is defined as type "Date" in the xcdatamodel.
当我从它创建的 sqlite 数据库中导出 sql 时,created_at 被定义为类型时间戳"并且值如下所示:
When I export the sql from the sqlite database it created, created_at is defined as type "timestamp" and the values look like:
290902422.72624
290902422.72624
. 前的九位数字.然后是一些分数.
Nine digits before the . and then some fraction.
这是什么格式?这不是纪元时间,也不是 julianday 格式.
What is this format? It's not epoch time and it's not julianday format.
时代将是:
1269280338.81213
1269280338.81213
julianday 将是:
julianday would be:
2455278.236746875(注意 . 前只有 7 位数字,而不是像我一样的 9 位)
2455278.236746875 (notice only 7 digits before the . not 9 like I have)
如何将 290902422.72624 之类的数字转换为纪元时间?谢谢!
How can I convert a number like 290902422.72624 to epoch time? Thanks!
推荐答案
首先,请注意 Core Data 文档说你永远不应该接触 SQL 或它自己生成的值 - 如果这样做有可能使你的模型无效您对其进行更改,并且一开始就很难解析.
First, note that the Core Data documentation says you should never touch the SQL or values it generates on your own - doing so has the potential to invalidate your model if you make changes to it, and it's difficult to parse in the first place.
也就是说,您可能看到的是相对于格林威治标准时间 2001 年 1 月 1 日的日期.NSDate 指定单个原始方法 timeIntervalSinceReferenceDate
使用该时间作为其参考.反过来,Core Data 使用 NSDateAttributeType
来存储日期类型,它被定义为一个 NSDate 对象.
That said, what you may be seeing is dates relative to January 1, 2001 in GMT. The documentation for NSDate specifies that the single primitive method, timeIntervalSinceReferenceDate
, uses that time for its reference. Core Data, in turn, uses the NSDateAttributeType
to store date types, which is defined to be an NSDate object.
通过计算器计算您的价值会产生:
Running your value through a calculator produces:
290902422.72624 / 60 / 60 / 24 / 365.25 = 9.21814...
这是自该参考日期以来经过的年数.
which is about the number of years that's elapsed since that reference date.
如果您真的需要将该值解析回一个纪元时间,您可以使用方法 initWithTimeIntervalSinceReferenceDate:
和 SQLite 存储的数字来获取 NSDate,然后调用 timeIntervalSince1970
返回纪元秒数(在 NSTimeInterval 结构中).
If you really need to parse that value back into an epoch time you can use the method initWithTimeIntervalSinceReferenceDate:
with your SQLite-stored number to get an NSDate, then call timeIntervalSince1970
to get epoch seconds back (in an NSTimeInterval struct).
这篇关于iPhone SDK Core Data 系统如何将日期类型存储到sqlite?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!