Objective-C 和 sqlite 的 DATETIME 类型 [英] Objective-C and sqlite's DATETIME type

查看:28
本文介绍了Objective-C 和 sqlite 的 DATETIME 类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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]);

你必须记住三件事:

  1. 在您的 SQLite 日期字段中,类型应为 DATETIME
  2. 存储和检索时的日期格式应相同
  3. 现在您可以按照自己的方式展示,但要遵循格式.下面给出了格式详细信息.

格式:

   '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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆