【问题标题】:How do I get the current hour using Cocoa?如何使用 Cocoa 获取当前时间?
【发布时间】:2016-03-22 22:30:26
【问题描述】:

如何使用 Objective-C 在 Cocoa 中获取当前小时数?

【问题讨论】:

    标签: objective-c cocoa


    【解决方案1】:

    首先,您应该阅读Dates and Times Programming Topics for Cocoa。这将使您很好地了解如何使用 Cocoa 中提供的各种日期/时间/日历对象来进行高级别的日期转换。

    但是,此代码片段将回答您的具体问题:

    - (NSInteger)currentHour
    {
        // In practice, these calls can be combined
        NSDate *now = [NSDate date];
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];
    
        return [components hour];
    }
    

    【讨论】:

    • 最好还是观看 WWDC 视频,看看本周的 NSHipster
    【解决方案2】:

    一种方法是使用 NSCalendar 和 NSDateComponents

    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];
    NSInteger hour = [components hour];
    

    【讨论】:

      【解决方案3】:

      我也是 Cocoa 的新手,我很高兴找到了这个。我还想补充一点,您可以轻松地将其设为在一个 NSDateComponents 对象中返回当前小时、分钟和秒的函数。像这样:

      // Function Declaration (*.h file)
      -(NSDateComponents *)getCurrentDateTime:(NSDate *)date;
      
      // Implementation
      -(NSDateComponents *)getCurrentDateTime:(NSDate *)date
      {
          NSDate *now = [NSDate date];
          NSCalendar *calendar = [NSCalendar currentCalendar];
          NSDateComponents *comps = [calendar components:NSHourCalendarUnit + NSMinuteCalendarUnit + NSSecondCalendarUnit fromDate:now];
          return comps;
      
      }
      
      // call and usage
      
      NSDateComponents *today = [self getCurrentDateTime:[NSDate date]];
              hour = [today hour];
              minute = [today minute];
              second = [today second];
      

      您可以看到 NSCalendar 对象中的 components 参数是一个有点明智的枚举,您可以使用 '+' 组合枚举值

      我只是想我会做出贡献,因为我能够使用这些示例来创建我的示例。

      【讨论】:

        【解决方案4】:
        [NSDate date]
        

        这是当前时间,根据需要解析出小时。您没有提供很多关于您所指的确切时间的详细信息 - 例如,格式化为当前时区?还是换一个?

        【讨论】:

          【解决方案5】:

          斯威夫特版本

          func currentHour() -> Int {
              let now = NSDate()
              let calendar = NSCalendar.currentCalendar()
              let components = calendar.components(.Hour, fromDate: now)
          
              return components.hour
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-12-25
            • 2011-04-06
            • 2013-12-30
            • 2010-11-07
            • 2021-04-29
            • 2011-02-16
            • 1970-01-01
            • 2021-01-28
            相关资源
            最近更新 更多