Swift
Date
Swift Programming
iOS Development
Date Object

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

Creating a Date in Swift is easy, but using it correctly depends on understanding what Date represents. A Date is an absolute instant in time, not a formatted string and not a calendar description by itself. Most date bugs come from mixing those concerns together.

Create the Current Time

The simplest way to create a Date is to ask for the current instant.

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

This is the right choice for timestamps, event recording, and measuring durations.

Create a Date from an Epoch Timestamp

If an API or database gives you Unix time, create the date from that numeric value.

swift
1import Foundation
2
3let timestamp: TimeInterval = 1_709_555_200
4let date = Date(timeIntervalSince1970: timestamp)
5print(date)

If the source uses milliseconds instead of seconds, divide by one thousand first:

swift
let milliseconds: Double = 1_709_555_200_000
let dateFromMilliseconds = Date(timeIntervalSince1970: milliseconds / 1000)
print(dateFromMilliseconds)

Confusing seconds with milliseconds is one of the most common date conversion mistakes in mobile apps.

Parse a Known String Format

When you need to build a Date from text, use a DateFormatter with explicit locale and timezone settings.

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
8if let parsed = formatter.date(from: "2026-03-04 14:30:00") {
9    print(parsed)
10}

en_US_POSIX is important for fixed-format parsing because it avoids locale-dependent surprises.

Parse ISO 8601 Dates for APIs

Web APIs commonly use ISO 8601 timestamps, and Swift provides a dedicated formatter for them.

swift
1import Foundation
2
3let isoFormatter = ISO8601DateFormatter()
4isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
5
6let input = "2026-03-04T14:30:00.123Z"
7if let isoDate = isoFormatter.date(from: input) {
8    print(isoDate)
9}

If your API sometimes includes fractional seconds and sometimes does not, you may need either two formatters or a fallback parsing path.

Build a Date from Calendar Components

If the source information is human calendar data such as year, month, day, and hour, use DateComponents and Calendar.

swift
1import Foundation
2
3var components = DateComponents()
4components.year = 2026
5components.month = 3
6components.day = 4
7components.hour = 9
8components.minute = 15
9components.timeZone = TimeZone(identifier: "America/Toronto")
10
11let calendar = Calendar(identifier: .gregorian)
12if let scheduled = calendar.date(from: components) {
13    print(scheduled)
14}

This is the correct approach for schedules, reminders, and user-entered dates.

Separate Storage from Display

Once you have a Date, keep formatting separate from storage. Use DateFormatter only when you need a human-readable string.

swift
1import Foundation
2
3let formatter = DateFormatter()
4formatter.dateStyle = .medium
5formatter.timeStyle = .short
6formatter.locale = Locale.current
7formatter.timeZone = TimeZone.current
8
9print(formatter.string(from: Date()))

The same stored Date can appear differently for users in different locales and timezones, and that is expected.

Test with Explicit Assumptions

Date code should be tested with fixed inputs and explicit timezone assumptions. Avoid tests that depend on the machine's current clock or local timezone.

A practical test strategy includes:

  • fixed ISO strings
  • fixed epoch timestamps
  • daylight-saving boundaries
  • known timezone conversions

That is what turns date handling from "it seems fine on my laptop" into something reliable.

Common Pitfalls

The biggest pitfall is treating Date as if it already contains a human-readable month, day, and timezone representation. It does not.

Another common issue is parsing strings with default locale and timezone settings. That makes behavior vary across devices and regions.

People also mix milliseconds and seconds when reading timestamps, which produces wildly incorrect results that still look syntactically valid.

Summary

  • 'Date in Swift represents an absolute instant in time.'
  • Use Date() for the current time and epoch initializers for Unix timestamps.
  • Parse strings with explicit locale and timezone settings.
  • Use ISO8601DateFormatter for common API timestamp formats.
  • Keep storage, parsing, and display as separate concerns to avoid recurring date bugs.

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.