Swift
programming
date and time
iOS development
Swift tutorial

How to get the hour of the day with Swift?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Swift, the correct way to extract the hour from a Date is to use Calendar, not string formatting or manual parsing. The hour value depends on calendar and time zone context, so those choices matter if your app works across regions or stores UTC timestamps. For most applications, Calendar.current.component(.hour, from:) is the simplest and safest solution.

Get the Current Hour with Calendar

Date represents an absolute point in time, while Calendar interprets that point into human components such as year, month, and hour.

swift
1import Foundation
2
3let now = Date()
4let hour = Calendar.current.component(.hour, from: now)
5
6print(hour)

This returns an integer from 0 to 23 in the user’s current calendar and time zone.

Extract the Hour from Any Specific Date

The same approach works for stored timestamps, API results, and scheduled events.

swift
1import Foundation
2
3let formatter = ISO8601DateFormatter()
4let date = formatter.date(from: "2026-03-07T14:30:00Z")!
5
6let localHour = Calendar.current.component(.hour, from: date)
7print(localHour)

Because the input is UTC but Calendar.current uses the device’s current settings, the displayed hour may differ from the literal 14 in the string.

Control the Time Zone Explicitly

If the app needs the hour in a specific time zone rather than the user’s current one, configure the calendar before extracting components.

swift
1import Foundation
2
3let formatter = ISO8601DateFormatter()
4let date = formatter.date(from: "2026-03-07T14:30:00Z")!
5
6var calendar = Calendar(identifier: .gregorian)
7calendar.timeZone = TimeZone(identifier: "America/Toronto")!
8
9let torontoHour = calendar.component(.hour, from: date)
10print(torontoHour)

This is important for scheduling, reporting, and server-side timestamps where device-local interpretation would be misleading.

Get Multiple Components at Once

If you need hour plus related parts such as minute or weekday, request a DateComponents set once rather than multiple separate calls.

swift
1import Foundation
2
3let now = Date()
4let components = Calendar.current.dateComponents([.hour, .minute, .weekday], from: now)
5
6print(components.hour ?? -1)
7print(components.minute ?? -1)
8print(components.weekday ?? -1)

This is cleaner when you are building time-based UI or business rules from the same source date.

It also makes the code easier to extend later if the logic grows from “what hour is it” into “what hour, weekday, and minute is it in this business calendar”.

Do Not Confuse Hour Extraction with Display Formatting

If the goal is to show time to the user, DateFormatter is usually better than manually extracting the hour.

swift
1import Foundation
2
3let formatter = DateFormatter()
4formatter.timeStyle = .short
5formatter.dateStyle = .none
6
7print(formatter.string(from: Date()))

Use Calendar when you need the numeric hour for logic. Use DateFormatter when you need localized text for display.

Common Use Cases

Hour extraction is often used for:

  • Greeting logic such as morning or evening messages.
  • Quiet hours and notification windows.
  • Analytics bucketing by local hour.
  • Business rules like “submit before 17:00”.

In all of these cases, document which time zone the rule uses. “Current hour” is ambiguous unless you define the calendar context clearly.

Testing Time-Based Logic

Time-related bugs are often caused by hidden assumptions about locale or time zone. Make tests explicit.

swift
1import Foundation
2
3var calendar = Calendar(identifier: .gregorian)
4calendar.timeZone = TimeZone(secondsFromGMT: 0)!
5
6let formatter = ISO8601DateFormatter()
7let date = formatter.date(from: "2026-03-07T23:15:00Z")!
8
9let hour = calendar.component(.hour, from: date)
10print(hour)  // 23

This prevents tests from changing behavior based on the machine running them.

The same rule applies to production code that runs on servers or background jobs. If the business rule means UTC hour or a fixed regional hour, express that explicitly instead of relying on Calendar.current.

Common Pitfalls

  • Using DateFormatter string parsing for business logic instead of Calendar.
  • Forgetting that Date is absolute and the hour depends on interpretation context.
  • Assuming the hour in an ISO string is the same hour the user should see locally.
  • Writing tests that depend on the developer machine’s time zone.
  • Hardcoding 12-hour display assumptions when you really need 24-hour numeric values.

Summary

  • Use Calendar.component(.hour, from:) to get the hour from a Date.
  • Treat time zone and calendar as part of the logic, not as incidental details.
  • Use DateComponents when several time parts are needed together.
  • Use DateFormatter for user-facing display, not hour-based business rules.
  • Write tests with explicit time zones to keep date logic predictable.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.