Swift
Date object
programming
iOS development
time management

How do you create a Swift Date object?

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, Date represents a moment in time, not a calendar-friendly year-month-day structure. The main skill is choosing the right construction method: current time, date components, parsed string, or a relative offset from another date.

Create the Current Date and Time

If you need the current moment, initialize Date directly.

swift
1import Foundation
2
3let now = Date()
4print(now)

This value is timezone-independent internally. When you print it, Foundation formats it for display, but the stored value is still just a timestamp.

Build a Date from Calendar Components

When you know the year, month, day, or hour, use DateComponents together with a Calendar. This is usually safer than assembling a string and parsing it.

swift
1import Foundation
2
3var components = DateComponents()
4components.year = 2026
5components.month = 3
6components.day = 11
7components.hour = 9
8components.minute = 30
9
10let calendar = Calendar(identifier: .gregorian)
11let meetingDate = calendar.date(from: components)
12print(meetingDate as Any)

This style is useful for local reminders, recurring schedule calculations, and business rules based on calendar fields.

Parse a Date from a String

If input comes from an API or a text field, use a formatter. The formatter must match the actual input string exactly.

swift
1import Foundation
2
3let formatter = DateFormatter()
4formatter.locale = Locale(identifier: "en_US_POSIX")
5formatter.timeZone = TimeZone(secondsFromGMT: 0)
6formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
7
8let raw = "2026-03-11 14:45:00"
9let parsedDate = formatter.date(from: raw)
10print(parsedDate as Any)

The en_US_POSIX locale is important when parsing fixed-format strings. Without it, user locale rules can change parsing behavior unexpectedly.

Create Relative Dates

Sometimes you do not need a fixed calendar date. You just need a point in time relative to now or to another date.

swift
1import Foundation
2
3let oneHourFromNow = Date(timeIntervalSinceNow: 3600)
4let oneDayAgo = Date(timeIntervalSinceNow: -86400)
5
6print(oneHourFromNow)
7print(oneDayAgo)

For calendar-aware offsets such as one month later, use Calendar rather than raw seconds. A month is not always a fixed number of seconds.

swift
1import Foundation
2
3let now = Date()
4let nextMonth = Calendar.current.date(byAdding: .month, value: 1, to: now)
5print(nextMonth as Any)

Convert Dates for Display

A Date by itself is not intended for direct user-facing formatting. Use a formatter when showing it in the UI.

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

That separation matters: Date stores a moment, while the formatter decides how people see it.

Use ISO8601DateFormatter for API Timestamps

When the input is an ISO 8601 timestamp, use the dedicated formatter instead of a custom pattern.

swift
1import Foundation
2
3let isoFormatter = ISO8601DateFormatter()
4let apiDate = isoFormatter.date(from: "2026-03-11T15:00:00Z")
5print(apiDate as Any)

That keeps API parsing shorter and avoids mistakes around timezone indicators.

Compare and Store Dates Cleanly

Once a Date exists, compare dates directly or store them as raw values in your model layer. Avoid converting to strings just to compare or persist them. Strings are for input and display, not for internal time logic.

swift
1import Foundation
2
3let start = Date()
4let end = Date(timeIntervalSinceNow: 1800)
5print(start < end)

Common Pitfalls

  • Treating Date as if it already contains calendar fields such as month and weekday.
  • Parsing fixed-format strings without setting en_US_POSIX, which can break on different locales.
  • Using raw second offsets when the requirement is calendar-aware, such as one month later.
  • Forgetting timezone behavior when parsing server timestamps.
  • Printing Date directly in the UI instead of formatting it for people.

Summary

  • Use Date() for the current moment.
  • Use DateComponents and Calendar for specific calendar dates.
  • Use DateFormatter or ISO8601DateFormatter when parsing strings.
  • Use Calendar for month and day arithmetic, not raw seconds.
  • Format dates separately for display so timezone and locale handling stay correct.

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.