Get hours, minutes and seconds from Date with Swift
This is something that I have had to do a few times, but I find that it is one of those things that I always forget how to do. So I decided to write a post showing how to get the hour
, minutes
and second
using Date
.
The first thing we need to do is to create a new instance of Date
, as well as get the current Calendar
. To do that we can use the following code:
let date = Date()
var calendar = Calendar.current
After that we just need to decide what components we want. In this case we are going to use hour
, minute
and second
. There are more, the full list of Calendar
components include: era
, year
, month
, day
, hour
, minute
, second
, weekday
, weekdayOrdinal
, quarter
, weekOfMonth
, weekOfYear
, yearForWeekOfYear
, nanosecond
, calendar
and timeZone
.
To use any of these values we need to use our calendar
that we have. So to get the hour
, minute
and second
all we need to do is the following:
let hour = calendar.component(.hour, from: date)
let minute = calendar.component(.minute, from: date)
let second = calendar.component(.second, from: date)
And that is pretty much it. One issue with this is that if the hour, minute or second is smaller than 10, it will not prefix the value with a 0.
If you want, you can also set the timeZone
of the calendar. To do that you create a new TimeZone
instance with the time zone identifier you want, and then you set the timeZone
property on the calendar
.
Setting a timeZone
is as simple as:
if let timeZone = TimeZone(identifier: "EST") {
calendar.timeZone = timeZone
}
This needs to be done before you get the calendar.component
otherwise it will use the default timeZone
.
Full source:
let date = Date()
var calendar = Calendar.current
if let timeZone = TimeZone(identifier: "EST") {
calendar.timeZone = timeZone
}
let hour = calendar.component(.hour, from: date)
let minute = calendar.component(.minute, from: date)
let second = calendar.component(.second, from: date)
print("\(hour):\(minute):\(second)")