如何使用NSDate在Swift 3中获得时间(小时,分钟,秒)?


Answers:


164

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)")

像这样,您可以通过传递相应的信息来获取时代,年,月,日等。


97

迅捷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)")

斯威夫特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 ...”
怎么

1
您的要求对我不清楚,如何添加非成员类型 Calendar.Component?考虑您的日期是在“ 02/12/15,16:46”之后,其中秒不可用,并且您尝试使用Components提取秒,0在这种情况下它将返回您。
Dipen Panchasara

我发现了我的问题...我已经声明了一个名为struct的结构Calendar,该结构Calendar.Component明显受到干扰。
netigger

25
let date = Date()       
let units: Set<Calendar.Component> = [.hour, .day, .month, .year]
let comps = Calendar.current.dateComponents(units, from: date)

21

斯威夫特4

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


5
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)

5

迅捷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 

4

为了获得最佳效果,我创建了以下功能:

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

就是这样...


2
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

1

对于想在多个课程中使用当前日期的人来说,这可能很方便。

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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.