Objective-C和sqlite的DATETIME类型 [英] Objective-C and sqlite's DATETIME type
问题描述
我有一个sqlite3表,试图将其映射到Objective-C中的对象.该表的一个属性是"completed_at",该属性存储为DATETIME.
I have a sqlite3 table that I'm trying to map to an object in objective-C. One attribute of the table is 'completed_at' which is stored as a DATETIME.
我想在我的Objective-C类(继承自NSObject)上创建一个属性,该属性将很好地映射到'completed_at'属性.
I want to create a property on my objective-C class (which inherits from NSObject) that will map well to the 'completed_at' attribute.
Objective-C具有NSDate类型,但是我不确定是否可以直接映射?
Objective-C has an NSDate type but I'm not sure if that will map directly?
推荐答案
我在这里仅分享有关日期格式的核心内容,以保存和检索要显示的数据.如果您对此代码段有任何疑问,那么我将分享我在项目中使用的完整代码.
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.
保存数据时,请按照以下方式将日期值绑定到sql语句中:
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)]];
现在您有了一个NSDate类型的变量myDate,可以用自己的方式呈现它:
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]);
您必须记住三件事:
- 在您的SQLite日期字段中,类型应为DATETIME
- 存储和检索时的日期格式应该相同
- 现在,您可以按照自己的方式显示,但要遵循格式.下面是格式详细信息.
格式:
'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
这篇关于Objective-C和sqlite的DATETIME类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!