iphone - 将日期保存到 SQLite

标签 iphone ios xcode sqlite

-(void)save:(id)sender
{
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];

if (sqlite3_open(dbpath, &expenseDB) == SQLITE_OK)
{

    NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO ADDEXPENSE(date, description, category, amount) VALUES (\"%@\", \"%@\", \"%@\",\"%@\")", fieldOne.text, fieldTwo.text,fieldThree.text , fieldFour.text];

    const char *insert_stmt = [insertSQL UTF8String];

    sqlite3_prepare_v2(expenseDB, insert_stmt, -1, &statement, NULL);
    if (sqlite3_step(statement) == SQLITE_DONE)
    {
      status.text = @"saved"
    } 
    else 
    {
       status.text = @"Failed"
    }
    sqlite3_finalize(statement);
    sqlite3_close(expenseDB);
}
}

这种方法对我来说很好用。但是如何将它保存为日期而不是字符串?
我尝试了几种方法,但对我没有用。
因为我是编码新手。有人请帮我写一段代码
u u u u u u u u 这是我使用的日期选择器。
UIDatePicker *picker = (UIDatePicker *)sender;
NSDate *dateSelected = [picker date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd.MM.yyyy"];
self.fieldOne.text = [dateFormatter stringFromDate:dateSelected];

最佳答案

SQLLite 没有日期数据类型,因此您必须将其保存为文本或数字。我个人使用 text 方法,我的代码在插入或更新时将任何日期转换为文本,并在选择时将其转换回。

所以从我使用的日期开始

[self.dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *dateString = [self.dateFormatter stringFromDate:date];

将其转换回来
[self.dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSDate *theDate = [self.dateFormatter dateFromString:ds];

我将值保留为日期,直到我想要显示它为止。

您的代码示例需要一些思考,因为 iOS 开发中的关键概念之一是 MVC,这意味着您应该尝试将 View 与模型分开。理想情况下,您应该有一个对象,其中存储了数据。你的 View 知道如何显示数据,你的 Model 知道如何存储和检索数据。

值得研究,因为它使代码更易于维护和扩展。

关于iphone - 将日期保存到 SQLite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8165033/

相关文章:

iphone - 如何在 itunesconnect 中重命名您的应用程序?

iphone - 如何从左翻转?

iPhone : How to sync data with the web-service when internet is reachable?

ios - AppDelegate 函数未加载 TableView Controller

ios - swift : How to create a UIView with transparent circle in the middle?

ios - IBM Mobilefirst 7.0 - 我们可以将 Estimote Ibeacons 与 IBM MobileFirst 集成吗

ios - Xcode 设置 View Controller 身份 iOS OpenGL

ios - 代码签名未显示配置文件 - Xcode 5.1。

ios - Swift 3 URLSession 发送空请求

iOS 配置门户 - 通配符应用程序 ID 以及显式应用程序 ID