可可 - 存储时间

时间:2013-12-05 15:44:17

标签: objective-c cocoa nsdate nsdateformatter

我有一个日期选择器,只显示时间,“00:00”。我需要将此保存为日期还是有更好的方法?

如果作为约会,我应该使用像01/01/2000 05:45这样的东西吗?

2 个答案:

答案 0 :(得分:2)

如果只是您关心的时间而且您永远不需要处理时区或其他调整,您可以将时间存储为“午夜以来的秒数”。这仅适用于您的时间总是“本地”时间。

但由于UIDatePicker会给你时间NSDate(日期部分默认为“今天”),因为你可以轻松使用NSDateFormatter来显示时间部分,您可能希望坚持使用NSDate

但是使用NSDate可能是排序的问题,因为日期的排序也将包括日期部分。您还需要考虑如何计划持久保存这些值。

答案 1 :(得分:0)

这取决于您想要存储的方式。这是分隔日期和时间的代码。

NSDateFormatter *dateFormatterDateOnly = nil;
NSDateFormatter *dateFormatterTimeOnly = nil;
NSString *tempdateStringDateOnly = @"";
NSString *tempdateStringTimeOnly= @"";
if (dateFormatterDateOnly == nil) {
    dateFormatterDateOnly = [[NSDateFormatter alloc] init];
    [dateFormatterDateOnly setDateFormat:@"MM-dd-yyyy"];
}
if (dateFormatterTimeOnly == nil) {
    dateFormatterTimeOnly = [[NSDateFormatter alloc] init];
    [dateFormatterTimeOnly setDateFormat:@"hh:mm a"];
}

tempdateStringDateOnly  = [NSString stringWithFormat:@"%@", [dateFormatterDateOnly stringFromDate:selectedDate]];   
tempdateStringTimeOnly  = [NSString stringWithFormat:@"%@", [dateFormatterTimeOnly stringFromDate:selectedDate]];