【问题标题】:I want to Save only Time instead of Date and time in coredata objective-c我想在 coredata Objective-c 中只保存时间而不是日期和时间
【发布时间】:2017-10-27 18:49:54
【问题描述】:

我想要像 hh:mm:ss (10:45:32) 而不是像 2017-10-24 10:45:32 +0600,如何在 Core Data 中实现?

- (IBAction)SaveTasks:(UIButton *)sender
{

    [dateformater setDateFormat:@"dd/MM/yyyy"];

    NSDate *date = [dateformater dateFromString:datepictxt.text];

    NSManagedObjectContext *context = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext;

    NSManagedObject *entityNameObj = [NSEntityDescription insertNewObjectForEntityForName:@"Tasks" inManagedObjectContext:context];

    [entityNameObj setValue:tasks.text forKey:@"taskname"];
    [entityNameObj setValue:date forKey:@"date"];

    [((AppDelegate*)[[UIApplication sharedApplication] delegate]) saveContext];

    NSError *error = nil;
    if (![context save:&error])
    {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

    }else {
        NSLog(@"Your Data has been Saved!");
    }



}

【问题讨论】:

  • 如果你想保存 "10:45:32" 的 NSString 则将其保存为字符串...不要将其转换为 NSDate 对象。
  • 那我怎么跟时间比较呢。
  • 所以只节省时间是不可能的..
  • OK - 如果您想比较“时间”而不是“字符串”,那么您需要了解什么是日期。你从datepictxt 得到一个字符串,你想把它保存为“时间”吗?试着解释一下你想做什么...
  • 我正在制作一个保存 TaskName、TaskDate 和 Tasktime 的应用程序......然后我想在时间到来时通知他们(如警报)......

标签: ios objective-c core-data nsdate


【解决方案1】:

如果您有一个具有 Date 类型的 CoreData 实体,则 Date 默认为 NSDate,尽管您可以在 Data Model Inspector(右窗格,最右边的选项卡)中为属性使用标量类型。

无论哪种方式,该日期类型都将包含完整的日期信息——日期和时间。

如果您只想打印时间,可以执行以下操作:

NSDate *now = [NSDate date];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"hh:mm:ss";
NSString *timeString = [formatter stringFromDate:now];
NSLog(@"time:%@", timeString);
// prints: time:03:02:21

如果您只需要打印时间,请执行此操作。如果您还需要在 Core Data 实体上存储时间字符串,则需要为此添加一个 String 属性。

【讨论】:

  • 好的,谢谢,我会将时间保存为字符串
猜你喜欢
  • 1970-01-01
  • 2021-09-10
  • 2010-12-19
  • 2011-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多