How to get current time

I'm new to Xcode and want to know how to get the current time as a variable or constant (specifically the current hour and minute). I've tried using Date(), which is what most websites told me to use, but it doesn't seem to work. what do I need to type to get the time?

Answered by LanceLink42 in 679878022

Date() includes current date and time all in one package. You just need to extract the time parts from it. Have a look at Calendar class DateComponents method to get hour and minute as variables, or DateFormat() to just format them as a string. Examples:

import UIKit

// current date and time
let date = Date()

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

// DateFormatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm"
let hoursMinutesString = dateFormatter.string(from: date)
Accepted Answer

Date() includes current date and time all in one package. You just need to extract the time parts from it. Have a look at Calendar class DateComponents method to get hour and minute as variables, or DateFormat() to just format them as a string. Examples:

import UIKit

// current date and time
let date = Date()

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

// DateFormatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm"
let hoursMinutesString = dateFormatter.string(from: date)
How to get current time
 
 
Q