【问题标题】:Cocoa - Storing Time可可 - 储存时间
【发布时间】:2013-12-05 15:44:17
【问题描述】:

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

如果作为日期,我应该使用 01/01/2000 05:45 之类的内容吗?

【问题讨论】:

    标签: objective-c cocoa nsdate nsdateformatter


    【解决方案1】:

    如果只是您关心的时间并且您不需要处理时区或其他调整,您可以将您的时间存储为“自午夜以来的秒数”。这仅在您的时间始终是“本地”时间时才有效。

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

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

    【讨论】:

      【解决方案2】:

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

      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]];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-27
        • 2010-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        • 2020-04-08
        • 2015-09-04
        相关资源
        最近更新 更多