[datetime] How to get the current time as datetime

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?

This question is related to datetime swift

The answer is


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

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)

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

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

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

You can get from Dateformatter

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

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

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)


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.


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

In Swift 3,

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

    let hour = calendar.component(.hour, from: date)

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

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


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.


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


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

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

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

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

One line Swift 5.2

let date = String(DateFormatter.localizedString(from: NSDate() as Date, dateStyle: .medium, timeStyle: .short))


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"

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

if you just need the hour of the day

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

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

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.


Swift 5

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

and Call function printTimestamp()