Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

Objective-C and sqlite's DATETIME type

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.

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 has an NSDate type but I'm not sure if that will map directly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...