106

How can you determine the hour, minute and second from NSDate class in Swift 3?

In Swift 2:

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

Swift 3?

Marcus Leon
  • 55,199
  • 118
  • 297
  • 429
SaRaVaNaN DM
  • 4,390
  • 4
  • 22
  • 30
  • See also [this answer](http://stackoverflow.com/a/33343958/3681880). – Suragch Oct 08 '16 at 15:43
  • 3
    Possible duplicate of [How to get the current time as datetime](http://stackoverflow.com/questions/24070450/how-to-get-the-current-time-as-datetime) – Eric Aya Nov 19 '16 at 11:12

11 Answers11

197

In Swift 3.0 Apple removed 'NS' prefix and made everything simple. Below is the way to get hour, minute and second from 'Date' class (NSDate alternate)

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

Like these you can get era, year, month, date etc. by passing corresponding.

SaRaVaNaN DM
  • 4,390
  • 4
  • 22
  • 30
110

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)")
Dipen Panchasara
  • 13,480
  • 5
  • 47
  • 57
  • What if I get `'Component' is not a member type of 'Calendar'` on line `let unitFlags...`` – netdigger Sep 21 '16 at 09:36
  • 1
    What you are asking is not clear to me, How could you add non member type in `Calendar.Component`? Consider your date is following "02/12/15, 16:46" where seconds are not available and you try to extract seconds using Components it will return you `0` in that case. – Dipen Panchasara Sep 21 '16 at 11:12
  • I found my issue... I had declared a struct named `Calendar` which interfered with `Calendar.Component` obviously. – netdigger Sep 21 '16 at 11:13
27
let date = Date()       
let units: Set<Calendar.Component> = [.hour, .day, .month, .year]
let comps = Calendar.current.dateComponents(units, from: date)
Artem
  • 391
  • 3
  • 11
22

Swift 4

    let calendar = Calendar.current
    let time=calendar.dateComponents([.hour,.minute,.second], from: Date())
    print("\(time.hour!):\(time.minute!):\(time.second!)")
Hamed
  • 1,678
  • 18
  • 30
19

In Swift 3 you can do this,

let date = Date()
let hour = Calendar.current.component(.hour, from: date)
Mohammad Tarem
  • 201
  • 2
  • 4
12

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

Usage:

print(Date().get(.year)) // => 2020
print(Date().get(.month)) // => 08
print(Date().get(.day)) // => 18 
Ahmadreza
  • 6,950
  • 5
  • 50
  • 69
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)
ronak patel
  • 400
  • 5
  • 17
4

For best useful I create this function:

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

You simply call it wherever you want like this:

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

this is the Output:

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

if want only the time simply change :

dateFormatter.dateFormat  = "HH:mm:ss"

and this is the output:

Date = 17:27:30

and that's it...

Fabio
  • 5,432
  • 4
  • 22
  • 24
3
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
Deepak Tagadiya
  • 2,187
  • 15
  • 28
3

This might be handy for those who want to use the current date in more than one class.

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
    }
}

Usage

var time = ""
time = time.getCurrentTime()
print(time)   // 1900-12-09-12-59
budiDino
  • 13,044
  • 8
  • 95
  • 91
Celeste
  • 1,519
  • 6
  • 19
3

Swift 5+ Date extension to get Int value of any desired date component:

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

Usage:

let now = Date()
print(now.component(.year))  // 2021
print(now.component(.month)) // 12
print(now.component(.day))   // 30
budiDino
  • 13,044
  • 8
  • 95
  • 91