我想在coredata objective-c中仅保存时间而不是日期和时间

时间:2017-10-27 18:49:55

标签: ios objective-c core-data nsdate

我想要像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!");
    }



}

1 个答案:

答案 0 :(得分:2)

如果您有一个具有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属性。