Working with Dates in Swift: Foundation and DateFormatter

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is it and why is it needed?

Swift is a modern programming language from Apple for iOS, macOS, watchOS and tvOS. Working with dates is one of the key tasks in mobile and desktop development: from displaying time in chats to calculating deadlines in applications. Swift does not have a separate library for dates — all functionality is built into the Foundation framework. It provides the Date, DateFormatter, Calendar and DateComponents classes, which allow you to create, format, compare and manipulate dates.

How to install?

Foundation is part of the Swift standard library, so no installation is required. Simply import the module in your file: import Foundation. For working with dates in iOS/macOS projects (via Xcode), no additional dependencies are needed.

Main functions

  • Creating a date: Date() — current date and time; Date(timeIntervalSinceNow:) — date N seconds from now.
  • Formatting: DateFormatter — converting a date to a string (localized output) and back.
  • Date components: Calendar.current.dateComponents([.year, .month, .day], from: date) — extracting year, month, day.
  • Comparison: operators ==, <, >, as well as compare().
  • Manipulations: Calendar.current.date(byAdding: .day, value: 7, to: date) — adding 7 days.

Swift code example (iOS/macOS)

import Foundation

// Current datelet now = Date()print("Now: \\(now)")

// Formatting into a localized stringlet formatter = DateFormatter()formatter.dateStyle = .longformatter.timeStyle = .shortformatter.locale = Locale(identifier: "ru_RU")let formatted = formatter.string(from: now)print("Formatted date: \\(formatted)")

// Extracting the day of the weeklet calendar = Calendar.currentlet weekday = calendar.component(.weekday, from: now)print("Day of the week (1=Sunday): \\(weekday)")

// Adding 3 daysif let futureDate = calendar.date(byAdding: .day, value: 3, to: now) { print("In 3 days: \\(formatter.string(from: futureDate))")}

// Parsing a stringformatter.dateFormat = "yyyy-MM-dd"if let parsedDate = formatter.date(from: "2025-12-31") { print("Parsed: \\(parsedDate)")}

When to use?

Use the built-in Foundation tools whenever you need to work with dates in Swift: displaying time in the UI, calculating the difference between dates, creating calendars, reminders, timers, event logging. For complex scenarios (e.g., working with time zones or recurring events), combine DateComponents and Calendar. Alternative third-party libraries (e.g., SwiftDate) exist, but Foundation is sufficient for most projects.

Recommendations