7

我有一个 sqlite3 表,我试图将它映射到 Objective-C 中的一个对象。该表的一个属性是“completed_at”,它存储为 DATETIME。

我想在我的 Objective-C 类(继承自 NSObject)上创建一个属性,该属性将很好地映射到“completed_at”属性。

Objective-C 有一个 NSDate 类型,但我不确定它是否会直接映射?

4

4 回答 4

27

I am sharing here just the core things regarding date formatting for saving and retrieving the data for presentation. If you have any problem with this code snippet then I will share the full code that I used for my project.

When you save your data, bind your date value in the sql statement like this way:

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString=[dateFormat stringFromDate:[NSDate date]];

    sqlite3_bind_text(saveStmt, 1, [dateString UTF8String] , -1, SQLITE_TRANSIENT);

and when you retrieve data you have to write this code:

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *myDate =[dateFormat dateFromString:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)]];

now you have a variable myDate of NSDate type which you can render in your way:

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy hh:mm:ss a"];
    NSLog(@"My Date was : %@", [formatter stringFromDate:myDate]);

You must have to remember three things:

  1. In your SQLite date field type should be DATETIME
  2. Date format should be same when you store and when you retrieve
  3. Now you can show in your own way but following the format. Below the format details is given.

Format:

   'dd' = Day 01-31
   'MM' = Month 01-12
   'yyyy' = Year 2000
   'HH' = Hour in 24 hour
   'hh' = Hour in 12 hour
   'mm' = Minute 00-59
   'ss' = Second 00-59
   'a' = AM / PM
于 2011-08-18T13:57:33.807 回答
3

我对 Objective-C 的经验为零,但我通过谷歌搜索找到了Apple 的NSDate 类参考。通过链接页面上提供的信息,您应该能够弄清楚如何在 Objective-C 中操作 32 位纪元时间,这在 SQLite 中可以很好地工作。我可能会将 completed_at 列创建为 32 位时间的 INTEGER 类型。

SQLite 真的更喜欢 Julian 日期,它是浮点数。我还没有找到任何解释如何强迫 NSDate 类与 Julians 合作的文档。

timeIntervalSince1970看起来很有趣。

于 2008-11-19T18:03:54.877 回答
2

如果您试图影响演示,格式化程序很重要,但如果您将 if 用于内部存储,则您定义的字符串可能会破坏 DB 引擎使用该值进行计算、比较、排序等的能力。此外,如果您将有不同的客户端将日期值插入数据库中,您将不得不在任何地方编写转换函数。我使用了以下内容,它按预期工作(模式的列定义为 DATETIME):

dateExpires = [NSDate dateWithTimeIntervalSinceNow: sqlite3_column_double(queryStmt, 5)];

我在中央时区插入带有 Firefox 附加组件的 SQLITE3 db 作为“2010 年 4 月 12 日”。在 XCode 调试器中查看 'dateExpires' 的值显示为:

2010-04-12 23:19:48 -0500

果然,那是正确的时间。

此外,要插入 SQLITE DB,您将输入值[NSDate date]

于 2010-04-13T04:30:22.513 回答
2

这是几周前出现的:

在 iPhone 应用程序中将日期持久化到 SQLite3

于 2008-11-19T22:06:16.070 回答