Working with Dates and Time in Swift: A Complete Guide

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

Working with Dates and Times in Swift: From Basics to Advanced Techniques



Working with dates and times is one of the key tasks in developing applications for iOS and macOS. Swift provides a powerful and flexible set of tools for this purpose: Date, DateFormatter, Calendar, DateComponents, and TimeInterval. In this article, we will thoroughly examine each of them, show practical examples, and learn how to solve typical tasks such as formatting dates, calculating time differences, and working with time zones and calendars.



1. Basics: Date Class and TimeInterval



The basic type for representing a moment in time is Date. It stores the number of seconds elapsed since January 1, 2001, 00:00:00 UTC (Apple's reference date).



Creating and Comparing Dates:

import Foundation

// Current date and timelet now = Date()print("Now: \\(now)")

// Date based on a time interval (120 seconds from the current moment)let futureDate = Date(timeIntervalSinceNow: 120)print("In 2 minutes: \\(futureDate)")

// Date based on a fixed interval from the reference datelet specificDate = Date(timeIntervalSinceReferenceDate: 3600 * 24 * 365) // 1 year from 2001print("Approximate date: \\(specificDate)")

// Comparing datesif now < futureDate { print("Current date is earlier than the future date")}


TimeInterval is simply an alias for Double representing a number of seconds. It is used to calculate the difference between dates:

let startDate = Date()sleep(2) // Simulating a delaylet endDate = Date()

let elapsed: TimeInterval = endDate.timeIntervalSince(startDate)print("Elapsed \\(elapsed) seconds") // Will output ~2.0

// Reverse operationlet minutes: TimeInterval = 5 * 60let fiveMinutesLater = Date(timeInterval: minutes, since: startDate)


2. Formatting Dates with DateFormatter



To display a date to the user in a readable format, DateFormatter is used. It supports localization and many styles.



Basic Formatting:

let formatter = DateFormatter()formatter.locale = Locale(identifier: "ru_RU") // Russian localeformatter.timeZone = TimeZone.current       // Current time zone

// Standard stylesformatter.dateStyle = .fullformatter.timeStyle = .shortprint(formatter.string(from: Date())) // For example: "Friday, February 24, 2025, 2:30 PM"

formatter.dateStyle = .mediumformatter.timeStyle = .noneprint(formatter.string(from: Date())) // "Feb 24, 2025"


Custom Format:

formatter.dateFormat = "dd.MM.yyyy HH:mm"print(formatter.string(from: Date())) // "24.02.2025 14:30"

// Parsing a string into a datelet dateString = "25.12.2024 10:00"if let parsedDate = formatter.date(from: dateString) { print("Parsed date: \\(parsedDate)")}


Important: When parsing, always check that date(from:) does not return nil. An incorrect string format or locale mismatch will lead to an error.



3. Calendar Calculations: Calendar and DateComponents



The Calendar class encapsulates information about the calendar system (Gregorian, Islamic, Buddhist, etc.) and allows performing complex operations with dates. DateComponents is used to describe individual components of a date (year, month, day, hour, etc.).



Extracting Components:

let calendar = Calendar.currentlet components = calendar.dateComponents([.year, .month, .day, .weekday], from: Date())

print("Year: \\(components.year!)")print("Month: \\(components.month!)")print("Day: \\(components.day!)")print("Weekday: \\(components.weekday!)") // 1 - Sunday, 2 - Monday...

Blogs

Book Recommendations