【问题标题】:How to get time (hour, minute, second) in Swift 3 using NSDate?如何使用 NSDate 在 Swift 3 中获取时间(小时、分钟、秒)?
【发布时间】:2016-11-09 23:26:47
【问题描述】:

你如何确定 Swift 3 中 NSDate 类的小时、分钟和秒?

在 Swift 2 中:

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.Hour, fromDate: date)
let hour = components.hour

斯威夫特 3?

【问题讨论】:

标签: nsdate swift3


【解决方案1】:

Swift 3.0 中,Apple 移除了 'NS' 前缀,让一切变得简单。下面是从“日期”类(NSDate 替代)中获取小时、分钟和秒的方法

let date = Date()
let calendar = Calendar.current

let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("hours = \(hour):\(minutes):\(seconds)")

像这些你可以通过相应的获取时代、年、月、日等。

【讨论】:

    【解决方案2】:

    Swift 4.2 和 5

    // *** Create date ***
    let date = Date()
    
    // *** create calendar object ***
    var calendar = Calendar.current
    
    // *** Get components using current Local & Timezone ***
    print(calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date))
    
    // *** define calendar components to use as well Timezone to UTC ***
    calendar.timeZone = TimeZone(identifier: "UTC")!
    
    // *** Get All components from date ***
    let components = calendar.dateComponents([.hour, .year, .minute], from: date)
    print("All Components : \(components)")
    
    // *** Get Individual components from date ***
    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)
    let seconds = calendar.component(.second, from: date)
    print("\(hour):\(minutes):\(seconds)")
    

    Swift 3.0

    // *** Create date ***
    let date = Date()
    
    // *** create calendar object ***
    var calendar = NSCalendar.current
    
    // *** Get components using current Local & Timezone ***    
    print(calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date as Date))
    
    // *** define calendar components to use as well Timezone to UTC ***
    let unitFlags = Set<Calendar.Component>([.hour, .year, .minute])
    calendar.timeZone = TimeZone(identifier: "UTC")!
    
    // *** Get All components from date ***
    let components = calendar.dateComponents(unitFlags, from: date)
    print("All Components : \(components)")
    
    // *** Get Individual components from date ***
    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)
    let seconds = calendar.component(.second, from: date)
    print("\(hour):\(minutes):\(seconds)")
    

    【讨论】:

    • 如果我在网上得到'Component' is not a member type of 'Calendar' `let unitFlags...``
    • 您的问题我不清楚,您如何在Calendar.Component 中添加非会员类型?考虑您的日期在“02/12/15, 16:46”之后,其中秒数不可用,您尝试使用组件提取秒数,在这种情况下它将返回您0
    • 我发现了我的问题...我声明了一个名为 Calendar 的结构,它显然干扰了 Calendar.Component
    【解决方案3】:
    let date = Date()       
    let units: Set<Calendar.Component> = [.hour, .day, .month, .year]
    let comps = Calendar.current.dateComponents(units, from: date)
    

    【讨论】:

      【解决方案4】:

      斯威夫特 4

          let calendar = Calendar.current
          let time=calendar.dateComponents([.hour,.minute,.second], from: Date())
          print("\(time.hour!):\(time.minute!):\(time.second!)")
      

      【讨论】:

        【解决方案5】:

        在 Swift 3 中你可以做到这一点,

        let date = Date()
        let hour = Calendar.current.component(.hour, from: date)
        

        【讨论】:

        • 绝对是最简洁最简单的答案)
        【解决方案6】:

        Swift 5+

        extension Date {
            
            func get(_ type: Calendar.Component)-> String {
                let calendar = Calendar.current
                let t = calendar.component(type, from: self)
                return (t < 10 ? "0\(t)" : t.description)
            }
        }
        

        用法:

        print(Date().get(.year)) // => 2020
        print(Date().get(.month)) // => 08
        print(Date().get(.day)) // => 18 
        

        【讨论】:

          【解决方案7】:
          let hours = time / 3600
          let minutes = (time / 60) % 60
          let seconds = time % 60
          return String(format: "%0.2d:%0.2d:%0.2d", hours, minutes, seconds)
          

          【讨论】:

            【解决方案8】:

            为了最有用,我创建了这个函数:

            func dateFormatting() -> String {
                let date = Date()
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "EEEE dd MMMM yyyy - HH:mm:ss"//"EE" to get short style
                let mydt = dateFormatter.string(from: date).capitalized
            
                return "\(mydt)"
            }
            

            你只需像这样在任何你想要的地方调用它:

            print("Date = \(self.dateFormatting())")
            

            这是输出:

            Date = Monday 15 October 2018 - 17:26:29
            

            如果只想改变时间:

            dateFormatter.dateFormat  = "HH:mm:ss"
            

            这是输出:

            Date = 17:27:30
            

            就是这样……

            【讨论】:

              【解决方案9】:
              swift 4
              
              ==> Getting iOS device current time:-
              
              print(" ---> ",(Calendar.current.component(.hour, from: Date())),":",
                             (Calendar.current.component(.minute, from: Date())),":",
                             (Calendar.current.component(.second, from: Date())))
              
              output: ---> 10 : 11: 34
              

              【讨论】:

                【解决方案10】:

                这对于那些想在不止一堂课中使用当前日期的人来说可能很方便。

                extension String {
                
                    func  getCurrentTime() -> String {
                    
                        let date = Date()
                        let calendar = Calendar.current
                        
                        let year = calendar.component(.year, from: date)
                        let month = calendar.component(.month, from: date)
                        let day = calendar.component(.day, from: date)
                        let hour = calendar.component(.hour, from: date)
                        let minutes = calendar.component(.minute, from: date)
                        let seconds = calendar.component(.second, from: date)
                    
                        let realTime = "\(year)-\(month)-\(day)-\(hour)-\(minutes)-\(seconds)"
                    
                        return realTime
                    }
                }
                

                用法

                var time = ""
                time = time.getCurrentTime()
                print(time)   // 1900-12-09-12-59
                

                【讨论】:

                  【解决方案11】:

                  Swift 5+ Date 扩展以获取任何所需日期组件的Int 值:

                  extension Date {
                      func component(_ component: Calendar.Component) -> Int {
                          Calendar.current.component(component, from: self)
                      }
                  }
                  

                  用法:

                  let now = Date()
                  print(now.component(.year))  // 2021
                  print(now.component(.month)) // 12
                  print(now.component(.day))   // 30
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2021-06-06
                    • 1970-01-01
                    • 2014-03-21
                    相关资源
                    最近更新 更多