337

Just started with the playground. I'm trying to create a simple app.

I've created a date object like this:

var date = NSDate()

How can I get the current hour? In other languages I can do something like this:

var hour = date.hour

But I can't find any properties/methods like that. I've found a method, dateWithCalendarFormat. Should I use that? If so, HOW?

0

28 Answers 28

469

Update for Swift 3:

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

I do this:

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute

See the same question in objective-c How do I get hour and minutes from NSDate?

Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!

7
  • 4
    @YestayMuratov This handy webpage tells has all possible ways of formatting a date using the NSDateFormatter in Swift :) codingexplorer.com/…
    – Max
    Commented Jun 20, 2015 at 8:09
  • 15
    It looks that the new Swift version (2) you have to use something similar to let components = calendar.components(.NSCalendarUnit.Year.union(NSCalendarUnit.Minute), fromDate: date), the vertical slash cant be used here anymore. Commented Jun 24, 2015 at 19:09
  • 5
    let components = calendar.components(NSCalendarUnit.Year.union(NSCalendarUnit.Minute), fromDate: date) removed the extra '.' before NSCalendarUnit
    – cakes88
    Commented Oct 15, 2015 at 16:09
  • 46
    Swift 2.1: let components = calendar.components([ .Hour, .Minute, .Second], fromDate: date)
    – Obiwahn
    Commented Dec 11, 2015 at 10:29
  • 1
    In Swift 4: let components = NSCalendar.current.dateComponents([.hour, .minute], from: Date()); let (hour, minute) = (components.hour, components.minute) Commented Jun 11, 2019 at 17:53
236

Tested with Swift 4

Getting the Current Date and Time

You can get the current date and time as simply as this:

let currentDateTime = Date()

However, Date is a 64-bit floating point number measuring the number of seconds since the reference date of January 1, 2001 at 00:00:00 UTC. I can see that number for the current datetime by using

Date().timeIntervalSinceReferenceDate

At the time of this writing, it returned 497626515.185066, probably not exactly what you are looking for. Keep reading.

Creating Another Date and Time

Method 1

If you know the number of seconds before or after the reference date, you can use that.

let someOtherDateTime = Date(timeIntervalSinceReferenceDate: -123456789.0) // Feb 2, 1997, 10:26 AM

Method 2

Of course, it would be easier to use things like years, months, days and hours (rather than relative seconds) to make a Date. For this you can use DateComponents to specify the components and then Calendar to create the date. The Calendar gives the Date context. Otherwise, how would it know what time zone or calendar to express it in?

// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 1980
dateComponents.month = 7
dateComponents.day = 11
dateComponents.timeZone = TimeZone(abbreviation: "JST") // Japan Standard Time
dateComponents.hour = 8
dateComponents.minute = 34

// Create date from components
let userCalendar = Calendar.current // user calendar
let someDateTime = userCalendar.date(from: dateComponents)

Other time zone abbreviations can be found here. If you leave that blank, then the default is to use the user's time zone.

Method 3

The most succinct way (but not necessarily the best) could be to use DateFormatter.

let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let someDateTime = formatter.date(from: "2016/10/08 22:31")

The Unicode technical standards show other formats that DateFormatter supports.

Displaying the Date and Time

Method 1

If you want to just display certain components of the date or time you can use CalendarUnit to specify the components that you want to extract from Date.

// get the current date and time
let currentDateTime = Date()

// get the user's calendar
let userCalendar = Calendar.current

// choose which date and time components are needed
let requestedComponents: Set<Calendar.Component> = [
    .year,
    .month,
    .day,
    .hour,
    .minute,
    .second
]

// get the components
let dateTimeComponents = userCalendar.dateComponents(requestedComponents, from: currentDateTime)

// now the components are available
dateTimeComponents.year   // 2016
dateTimeComponents.month  // 10
dateTimeComponents.day    // 8
dateTimeComponents.hour   // 22
dateTimeComponents.minute // 42
dateTimeComponents.second // 17

See this answer also.

Method 2

Method 1 gave you the components, but it would be a lot of work to format those numbers for every style, language, and region. And you don't need to. This has already been done for you with the DateFormatter class.

// get the current date and time
let currentDateTime = Date()

// initialize the date formatter and set the style
let formatter = DateFormatter()
formatter.timeStyle = .medium
formatter.dateStyle = .long

// get the date time String from the date object
formatter.string(from: currentDateTime) // October 8, 2016 at 10:48:53 PM

Here is a continuation of the above code that shows more formatting options:

// "10/8/16, 10:52 PM"
formatter.timeStyle = .short
formatter.dateStyle = .short
formatter.string(from: currentDateTime)

// "Oct 8, 2016, 10:52:30 PM"
formatter.timeStyle = .medium
formatter.dateStyle = .medium
formatter.string(from: currentDateTime)

// "October 8, 2016 at 10:52:30 PM GMT+8"
formatter.timeStyle = .long
formatter.dateStyle = .long
formatter.string(from: currentDateTime)

// "October 8, 2016"
formatter.timeStyle = .none
formatter.dateStyle = .long
formatter.string(from: currentDateTime)

// "10:52:30 PM"
formatter.timeStyle = .medium
formatter.dateStyle = .none
formatter.string(from: currentDateTime)

Keep in mind, though, that this is for English with the region set to the US. For other languages and regions the formatting will look different.

Further study

0
61

You could also use NSDateFormatter's convenience method, e.g.,

func printTimestamp() {
  let timestamp = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .ShortStyle)
  print(timestamp)
}
printTimestamp() // Prints "Sep 9, 2014, 4:30 AM"
4
  • 2
    Creating an NSDateFormatter is expensive. You should create on and reuse it.
    – Rog
    Commented Mar 23, 2016 at 13:24
  • 3
    Swift 3: let timestamp = DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .short)
    – Brian Bird
    Commented Feb 23, 2017 at 23:13
  • 1
    A quicker way to get the current date time as a string is: Date().dateString("YYYY.MM.dd HH:mm:ss")
    – Dimitris
    Commented Oct 25, 2020 at 19:15
  • @Dimitris You mean yyyy.MM.dd HH:mm:ss. Do not use YYYY for year unless you have a clearly understood reason to do so. But it's far better to use date/time styles than a date format so that the resulting string is in a standard format for the user's locale.
    – HangarRash
    Commented Jul 14, 2023 at 15:07
53

Swift makes it really easy to create and use extensions. I create a sharedCode.swift file and put enums, extensions, and other fun stuff in it. I created a NSDate extension to add some typical functionality which is laborious and ugly to type over and over again:

extension NSDate
{
    func hour() -> Int
    {
        //Get Hour
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Hour, fromDate: self)
        let hour = components.hour

        //Return Hour
        return hour
    }


    func minute() -> Int
    {
        //Get Minute
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Minute, fromDate: self)
        let minute = components.minute

        //Return Minute
        return minute
    }

    func toShortTimeString() -> String
    {
        //Get Short Time String
        let formatter = NSDateFormatter()
        formatter.timeStyle = .ShortStyle
        let timeString = formatter.stringFromDate(self)

        //Return Short Time String
        return timeString
    }
}

using this extension you can now do something like:

        //Get Current Date
        let currentDate = NSDate()

        //Test Extensions in Log
        NSLog("(Current Hour = \(currentDate.hour())) (Current Minute = \(currentDate.minute())) (Current Short Time String = \(currentDate.toShortTimeString()))")

Which for 11:51 AM would write out:

(Current Hour = 11) (Current Minute = 51) (Current Short Time String = 11:51 AM)

0
44

You can use in swift 4 or 5 like bellow

let date = Date()
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = df.string(from: date)

Ouput will be like bellow

2019-12-20 09:40:08
30

Swift 4

let dateFormatter : DateFormatter = DateFormatter()
//  dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.dateFormat = "yyyy-MMM-dd HH:mm:ss"
let date = Date()
let dateString = dateFormatter.string(from: date)
let interval = date.timeIntervalSince1970

OUTPUT

2018-May-01 10:41:31

1
26

Swift 2 answer :

 let date = NSDate()
 let calendar = NSCalendar.currentCalendar()
 let components = calendar.components([.Hour, .Minute], fromDate: date)
 let hour = components.hour
 let minutes = components.minute
15

Swift 3:

static func currentTime() -> String {
    let date = Date()
    let calendar = Calendar.current
    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)
    return "\(hour):\(minutes)"
}

PS - not sure what the question means exactly by getting current time (and hour) as date time, but hopefully the above should explain enough to answer the question.

1
  • SaRaVaNaN DM's answer above had an extra '()' at the end of Calendar.current.
    – Charlie S
    Commented Oct 3, 2016 at 9:47
14

With Swift 5, Foundation offers many ways to get the hour value from a Date object. According to your needs, you may choose one of the four following Playground code snippets.


#1. Using Calendar dateComponents(_:from:) method

Calendar has a method called dateComponents(_:from:). dateComponents(_:from:) has the following declaration:

func dateComponents(_ components: Set<Calendar.Component>, from date: Date) -> DateComponents

Returns all the date components of a date, using the calendar time zone.

Usage:

import Foundation

let date = Date()
let dateComponents = Calendar.current.dateComponents([.hour], from: date)
let hour = dateComponents.hour
print(String(describing: hour)) // may print: Optional(13)

#2. Using Calendar component(_:from:) method

Calendar has a method called component(_:from:). component(_:from:) has the following declaration:

Returns the value for one component of a date.

func component(_ component: Calendar.Component, from date: Date) -> Int

Usage:

import Foundation

let date = Date()
let hour = Calendar.current.component(.hour, from: date)
print(hour) // may print: 13

#3. Using DateFormatter dateFormat property

DateFormatter has a property called dateFormat. dateFormat has the following declaration:

var dateFormat: String! { get set }

The date format string used by the receiver.

Usage:

import Foundation

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH"
let hour = dateFormatter.string(from: date)
print(hour) // may print: 13

#4. Using Dateformatter setLocalizedDateFormatFromTemplate(_:) method

Dateformatter has a method called setLocalizedDateFormatFromTemplate(_:). setLocalizedDateFormatFromTemplate(_:) has the following declaration:

func setLocalizedDateFormatFromTemplate(_ dateFormatTemplate: String)

Sets the date format from a template using the specified locale for the receiver.

Usage:

import Foundation

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("HH")
let hour = dateFormatter.string(from: date)
print(hour) // may print: 13
10

One line Swift 5.2

let date = String(DateFormatter.localizedString(from: Date(), dateStyle: .medium, timeStyle: .short))
1
  • There's no need to wrap it in String()
    – soundflix
    Commented Aug 7, 2023 at 13:21
7

if you just need the hour of the day

let calendar = NSCalendar.currentCalendar()
var hour = calendar.component(.Hour,fromDate: NSDate())
7

Using Date Formatter -Swift 3.0

//Date
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
let dateString = "Current date is: \(dateFormatter.string(from: Date() as Date))"
labelfordate.text = String(dateString)


//Time    
let timeFormatter = DateFormatter()
timeFormatter.timeStyle = .medium
let timeString = "Current time is: \(timeFormatter.string(from: Date() as Date))"
labelfortime.text = String(timeString)

Update Date and Time Every Seconds

override func viewDidLoad() {
super.viewDidLoad()

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(DateAndTime.action), userInfo: nil, repeats: true)

       }

func action()
    {
    //Date
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .medium
    let dateString = "Current date is: \(dateFormatter.string(from: Date() as Date))"
    labelfordate.text = String(dateString)


    //Time
    let timeFormatter = DateFormatter()
    timeFormatter.timeStyle = .medium
    let timeString = "Current time is: \(timeFormatter.string(from: Date() as Date))"
    labelfortime.text = String(timeString)

    }

Note: DateAndTime in the Timer code is the Class name.

0
6

In Swift 3,

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

    let hour = calendar.component(.hour, from: date)
1
  • let calendar = Calendar.current; let unitFlags: Set<Calendar.Component> = Set<Calendar.Component ([.hour]); let components = calendar.dateComponents(unitFlags, from: self) Commented Oct 4, 2016 at 8:09
5

I know there are a lot of answers but I think that mine may be more convenient to many

extension String {
    init(epoch: Double) {
        let date = Date(timeIntervalSince1970: epoch)

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd/MM/yyyy HH:mm:ssZZZ"

        self = dateFormatter.string(from: date)
    }
}
4

You can try this

func getTime() -> (hour:Int, min:Int, sec:Int) {
        let currentDateTime = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components([.Hour,.Minute,.Second], fromDate: currentDateTime)
        let hour = components.hour
        let min = components.minute
        let sec = components.second
        return (hour,min,sec)
    }

Now call that method and receive the date with hour,min and second

    let currentTime = self.getTime()
    print("Hour: \(currentTime.hour) Min: \(currentTime.min) Sec: \(currentTime.sec))")
4

Xcode 8.2.1 • Swift 3.0.2

extension Date {
    var hour: Int { return Calendar.autoupdatingCurrent.component(.hour, from: self) }
}

let date = Date()      // "Mar 16, 2017, 3:43 PM"
let hour = date.hour   // 15
3
  • or even just Date().hour Commented Jun 12, 2019 at 14:13
  • 1
    @NoodleOfDeath sure. That depends if a reference to the date is needed or not.
    – Leo Dabus
    Commented Jun 12, 2019 at 14:15
  • Very true, and I suppose for all intensive purposes, you would want to use the same date variable when generating related date components rather than a newly generated one for each date component Commented Jun 12, 2019 at 14:20
3

Expanding upon noiiv's epically concise solution, here is the even more concise Swift 3/4 implementation:

Swift 3/4

let components = Calendar.current.dateComponents([.hour, .minute], from: Date())
let (hour, minute) = (components.hour, components.minute)

Also, expanding upon Leo Dabus's extension we can have:

extension Date {

    func components(_ components: Set<Calendar.Component>) -> DateComponents {
        return Calendar.current.dateComponents(components, from: self)
    }

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

    var era: Int { return component(.era) }
    var year: Int { return component(.year) }
    var month: Int { return component(.month) }
    var day: Int { return component(.day) }
    var hour: Int { return component(.hour) }
    var minute: Int { return component(.minute) }
    var second: Int { return component(.second) }
    var weekday: Int { return component(.weekday) }
    var weekdayOrdinal: Int { return component(.weekdayOrdinal) }
    var quarter: Int { return component(.quarter) }
    var weekOfMonth: Int { return component(.weekOfMonth) }
    var weekOfYear: Int { return component(.weekOfYear) }
    var yearForWeekOfYear: Int { return component(.yearForWeekOfYear) }
    var nanosecond: Int { return component(.nanosecond) }
    var calendar: Calendar? { return components([.calendar]).calendar }
    var timeZone: TimeZone? { return components([.timeZone]).timeZone }

}

And use it like so:

let date = Date()
let (hour, minute) = (date.hour, date.minute)
4
  • no need to return an optional when getting something like year, month, day, etc... from a Date object. Btw Calendar component method is more appropriate for single component
    – Leo Dabus
    Commented Jun 12, 2019 at 14:48
  • @LeoDabus the optional is propogated because the DateComponents.year accessor is Int? Commented Jun 12, 2019 at 14:48
  • 1
    you can use Calendar component method which returns non optional. You can also force unwrap. It will never fail. But I would stick with the single element component method
    – Leo Dabus
    Commented Jun 12, 2019 at 14:49
  • @LeoDabus updated to use the component method for those accessors Commented Jun 12, 2019 at 14:54
3

Swift 5

func printTimestamp() {
    let timestamp = DateFormatter.localizedString(from: NSDate() as Date, dateStyle: .medium, timeStyle: .short)
    print(timestamp)
}

and Call function printTimestamp()

3

You can use Swift4 or Swift 5 bellow like:

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let current_date = dateFormatter.string(from: date)
print("current_date-->",current_date)

output like:

2020-03-02
3

Swift 5.5

Using the new Date.FormatStyle (available in macOS 12.0+ and iOS 15.0+):

let hour = Date.now.formatted(.dateTime.hour()) // returns a String
2

for only date in specific format

    let dateFormatter1 = NSDateFormatter()
    dateFormatter1.dateStyle = .MediumStyle
    dateFormatter1.timeStyle = .NoStyle
    dateFormatter1.dateFormat = "dd-MM-yyyy"
    let date = dateFormatter1.stringFromDate(NSDate())
1
  • 1
    Just a note, when using NSDateFormatter, these are expensive objects to create so you may want to use a lazy getter to re-use the same NSDateFormatter if you are using this code in a table or collection or something. The styles and format can be changed trivially where needed without impacting performance as much as re-creating these where ever they are needed. Cheers.! Commented Nov 22, 2017 at 0:17
1

You can create an extension on Date, that way you can easily call it in other files. Here is an example of a date extension that uses a computed property.

It will print it out: "Today, 4:55 PM"

extension Date {

    var formatter: DateFormatter? {
        let formatter = DateFormatter()
        formatter.dateStyle = .short
        formatter.timeStyle = .short
        formatter.doesRelativeDateFormatting = true

        return formatter
    }
}
1
func getCurrentDate() -> Date {
    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let dateInString  = dateFormatter.string(from: date)
    let dateinDate = dateFormatter.date(from: dateInString)
    return dateinDate!
}
0
0

You can get from Dateformatter

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:Date())
print(dateString)
0

Incase you need to format the answer in a particular way, you can easily use this method, the default = "dd-MM-yyyy".

extension Date {

   func today(format : String = "dd-MM-yyyy") -> String{
      let date = Date()
      let formatter = DateFormatter()
      formatter.dateFormat = format
      return formatter.string(from: date)
   }
}

Getting today's date can now be done using

Date().today() or Date().today("dd/MM/yyyy") 
0

SWIFT 4:

extension Date
{
    func hour() -> Int
    {
    //Get Hour
    let calendar = Calendar.current
    let components = calendar.component(.hour, from: self)
    let hour = components

    //Return Hour
    return hour
    }


    func minute() -> Int
    {
    //Get Minute
    let calendar = Calendar.current
    let components = calendar.component(.minute, from: self)
    let minute = components

    //Return Minute
    return minute
        }
}
2
  • please explain your answer.
    – MrMaavin
    Commented May 28, 2019 at 8:01
  • it extends integrated Date void... it puts hour variable of void Date to int value, as also minute variable, then returns hour and minute as int value. After that you can use it in code any way you want. For example, then you can call that values from DateComponents() - DateComponents.hour = Date.hour() - it gives you int value of current time. Commented May 29, 2019 at 20:14
0

Here is the SWIFT extension to get your current device location time (GMT).

func getGMTTimeDate() -> Date {
   var comp: DateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: self)
   comp.calendar = Calendar.current
   comp.timeZone = TimeZone(abbreviation: "GMT")!
   return Calendar.current.date(from: comp)!
}

Get now time:-

Date().getGMTTimeDate()
0

Works with Swift 5 (Xcode 10 & Xcode 11) (from France UTC)

func getCurrentDateTime() {
    let now = Date()
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "fr_FR")
    formatter.dateFormat = "EEEE dd MMMM YYYY HH:mm"
    myLabel.text = formatter.string(from: now)
    myLabel.font = UIFont(name: "HelveticaNeue-Light", size: 12)
    myLabel.textColor = UIColor.black
}

If you want to display only the date, set formatter.dateFormat

formatter.dateFormat = "EEEE dd MMMM YYYY"

To display only hours, change formatter.dateFormat to

formatter.dateFormat = "HH:mm"

Don't forget to add getCurrentDateTime() on viewDidLoad.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.